Possible Duplicate:
What is the difference between char a[] = “string”; and char *p = “string”;
I read this question somewhere.
char buf[]="hello";
char *buf="hello";
In terms of code generation, how do the two definitions of buf, differ?
There were four options to this and I marked
The first definition certainly allows the contents to buf to be safely modified at runtie; the second definition does not.
But as it turns out, the quiz master had the following to be marked as correct.
They do no differ-- they are functionally equivalent
Why is my choice wrong, since I can not do buf[3]='t' for the second case, but I can for the first one?
Thanks.
I didn’t know about the “life-time” of string literal in C hence my answer is not valid.
My answer:
Pointer types and vector/matrix types are interchangeable as long as memory management has been handled. Under the covers the compiler switches vector/matrix indexing operations into pointer arithmetic.
In this specific case the compiler counts the length of the string and allocates (stack) memory for both the vector/matrix as well as the pointer.
In other cases you have to manually allocate memory for the pointer in order to safely use it the way you use the vector/matrix. But syntactically the same applies for the vector/matrix because you have to specify it’s length
char buf[5]– it’s not quite as verbose as manual memory allocation but you do have to specify it.Edit:
The above answer explains the fact that in most cases pointers and vectors/matrixes are functionally interchangeable but they do have a different underlying structure (pointers need an extra memory location to store the address to).
And in the case of strings literals they are allocated and constant for the entire lifetime of the program which makes pointers to them keep on being valid without using memory allocation.