Wednesday, January 30, 2008

constant character array

Please ref this former post. You can use

char* cp = "hello";

and the compiler will accept it without complaint. This is technically an error because a character array literal is created by the compiler as a constant character array, and the result of the quoted character array is its starting address in memory. Modifying any of the characters in the array is a runtime error.

If you want to be able to modify the string, put it in an array:

char cp[] = "hello";

--thinkinginc++

char a[] = "string";
char *a = "string";


The declaration char a[] asks for space for 7 characters and see that its known by the name "a". In contrast, the declaration char *a, asks for a place that holds a pointer, to be known by the name "a". This pointer "a" can point anywhere.

char a[] = "string";

+----+----+----+----+----+----+------+
a: | s | t | r | i | n | g | '\0' |
+----+----+----+----+----+----+------+
a[0] a[1] a[2] a[3] a[4] a[5] a[6]


char *a = "string";

+-----+ +---+---+---+---+---+---+------+
| a: | *======> | s | t | r | i | n | g | '\0' |
+-----+ +---+---+---+---+---+---+------+
Pointer Anonymous array
[update: 4/28/08]

No comments:

Post a Comment