Some clarifications

Download Report

Transcript Some clarifications

Clarifications on Strings
• I received a number of queries
• Here are some explanations. For more details,
please surf the Internet.
1
What’s the difference?
The characters inside
the array can be
changed.
char string1[6] = "apple";
char *string2 = "apple";
string1
a
p
p
l
e
\0
The value inside this box, which is the address of the location that
contains ‘a’, cannot be changed. For ease of reference, we shall call
string1 a “constant” pointer/address.
string2
a
string2 is a pointer whose value can
be changed. That is, it can point to a
different location.
p
p
l
e
\0
However, this string literal is residing
in read-only memory, so its contents
2
cannot be changed.
Example #1
char word1[5] = "good";
char word2[4] = "bye";
word1
word1 = word2;
word2
×
g o o d
b y e
\0
\0
Attempt to change the value of constant
pointer word1! Not allowed!
strcpy(word1, word2);
word1 is not changed.
Characters in array word1 are
changed. Allowed!
word1
word2
y o
g
d
e \0
b o
b y e
\0
\0
3
Example #2 (Week 10 Discussion Q5)
char *fruit1 = "apple";
char *str1 = "yes"; fruit1
fruit1 = str1;
str1
fruit1 now points to “bye”. Allowed!
char *fruit2 = "apple";
char *str2 = "yes";
strcpy(fruit2, str2);fruit2
Pink boxes “apple” are in readonly memory; cannot
overwrite them with “bye”.
Not allowed!
str2
a p p l e
b y e
\0
a p p l e
b y e
\0
\0
\0
4