what's the difference between these two definitions

Apr 23rd, 2009 | Posted by yajin | Filed under kernel

I write this article because some guys are talking about it in CLF. The question is: what is the difference between the two following definitions:

A. const char temp[]="abc";

B. const char *temp="abc";

You may have your own answer already. But wait a moment, let me write some test cases first and you can see whether your answer is right or not. :)

(1) Test case 1

const char temp[]="abc";
int main()
{
temp[0]='c';
printf("temp %s \n",temp);
}
debian:~# gcc -o test test.c
test.c: In function `main':
test.c:8: error: assignment of read-only location `temp[0]'

(2) Test case 2

const char temp[]="abc";
char temp1[]="def";
int main()
{
temp = temp1;
printf("temp %s \n",temp);
}
debian:~# gcc -o test test.c
test.c: In function `main':
test.c:8: error: assignment of read-only variable `temp'

(3) Test case 3

const char* temp="abc";
char temp1[]="def";
int main()
{
temp = temp1;
printf("temp %s \n",temp);
}
debian:~# gcc -o test test.c
debian:~# ./test
temp def

(4) Test case 4

const char* temp="abc";
int main()
{
temp[0] = 'd';
printf("temp %s \n",temp);
}
debian:~# gcc -o test test.c
test.c: In function `main':
test.c:8: error: assignment of read-only location `*temp'

So the definition A means both temp and array is const and you can not change it. Definition B means temp points to a const string, which you can not change its content. But you can change temp itself.

Tags:
No comments yet.