This preview shows page 1. Sign up to view the full content.
Unformatted text preview: tant string' we should say
constant changing what the variable points at, but not
msg = 'd'; char* msg = "An error has occurred\n";
char* msg const char* msg = "abc";
Object Programming Here's a complication.
W e can put the keyword const iin another
position in our declaration.
char* const msg = "abc";
msg which is changing the contents of where it points. Object Programming char* m1;
char m2 = "def\n";
m1 = m2;
m1 = 'D'; This makes C++ ensure that we do not change
the value of the pointer – iit will always point at
the string "abc"
This means msg then acts much the same as a
Object Programming cout << m1;
cout << m2; m1 points at the string contained in m2.
If we want a copy of the string use strcpy.
Object Programming char* m1;
char m2 = "def\n"; Let's now look at structs. Consider
struct strcpy(m1,m2); struct Stype
}; m1 does not point anywhere. It has no space to
hold the string. Even if
char* m1 = "abc";
we still shouldn't do the copy as
• we are changing a constant string
• we are copying 5 chars where there is
space for 4
Object Programming Until we specify a value for SS, iit points at no
SS = &S; Stype* SS; or
typedef Stype* Sptr;
Object Programming To reference these locations indirectly using the
pointer SS, we must either dereference the pointer
(*SS).member1 will have SS pointing at S's location.
W e reference the members of the Stype
S.member3 or use the operator ->
means the component(or member) member1 of
component(or member) member1 of
what SS points at.
SS Object Programming Object Programming A pointer requires a value which is the address of
a data value.
data W e have already seen functions which return
pointer values although we probably haven't used
them as such.
them This may be the address of a constant, a global
variable, an automatic variable or a local variable.
variable, For example It can be passed as an argument, both by
reference and by value.
It can also be the return value of a function.
Object Programming char* strcpy(char*, const char*);
returns a pointer to the destination array.
But other functions in the string library require us
to use the pointer value.
to Object Programming char* ans;
ans = strchr("abcdef",'d');
cout << ans << endl;
<< ans << endl Consider
char* strchr(const char*,int);
which returns the location of the character
(second argument) in the string (first argument).
That location is a pointer to the character.
View Full Document
- Spring '14