2009年8月3日 星期一

unnamed array in C

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

A string literal (the formal term for a double-quoted string in C source) can be used in two slightly different ways:

1. As the initializer for an array of char, as in the declaration of char a[] , it specifies the initial values of the characters in that array (and, if necessary, its size).

char a[]="jeff";
char c[10]="jeff";

a[1]='b'; //OK
c[1]='b'; //OK

2. Anywhere else, it turns into an unnamed, static array of characters, and this unnamed array may be stored in read-only memory, and which therefore cannot necessarily be modified. In an expression context, the array is converted at once to a pointer. So the second declaration initializes p to point to the unnamed array's first element.

char *b="jeff";
b[1]='b';//Wrong!!

reference:

http://c-faq.com/decl/strlitinit.html

沒有留言: