C: differences between char pointer and array
arrays, c, pointers
Solution
True, but it's a subtle difference. Essentially, the former:
char amessage[] = "now is the time";
Defines an array whose members live in the current scope's stack space, whereas:
char *pmessage = "now is the time";
Defines a pointer that lives in the current scope's stack space, but that references memory elsewhere (in this one, "now is the time" is stored elsewhere in memory, commonly a string table).
Also, note that because the data belonging to the second definition (the explicit pointer) is not stored in the current scope's stack space, it is unspecified exactly where it will be stored and should not be modified.
As pointed out by Mark, GMan, and Pavel, there is also a difference when the address-of operator is used on either of these variables. For instance, &pmessage returns a pointer of type char**, or a pointer to a pointer to chars, whereas &amessage returns a pointer of type char(*)[16], or a pointer to an array of 16 chars (which, like a char**, needs to be dereferenced twice as litb points out).
Problem
Consider: ``` char amessage[] = "now is the time"; char *pmessage = "now is the time"; ``` I read from The C Programming Language, 2nd Edition that the above two statements don't do the same thing. I always thought that an array is an convenient way to manipulate pointers to store some data, but this is clearly not the case... What are the "non-trivial" differences between arrays and pointers in C?
Related problems
- In C, are arrays pointers or used as pointers?
- Default argument promotions in C function calls
- What is the type of string literals in C and C++?
- Difference between char *str="STRING" and char str[] = "STRING"?
- What is the difference between char array and char pointer in C?
- What is the difference between char s[] and char *s?
- Type casting char pointer to integer pointer
- extern declaration, T* v/s T[]