When is "pointer[]" format (in place of *pointer) acceptable? I was faddidling around trying new things and I just can't seem to use "s[]" like you did in the declaration after changing things. The first example works with s*, but the second one doesn't (because it has s[]).
First of all make clear that array are not pointers and pointers are not arrays.An array is a memory space holding a sequence of values of a specified type, a pointer is a single variable that holds the address of another variable of a specified type.
For its nature
any reference to an array (in plain words the name of the array variable) in C is treated as the address of the first element of the array. So De facto
the address of the first element have all properties of a pointer to a variable of the same type of the array. From this you can understand why array and pointers can share almost all the same operators, because by nature they behaves the same way.
Now let consider the subscript operator
[] (yes it is a generic operator not an array specific operator).
The subscript operator applies to a memory address, as a pointer or an array name, and dereferences the value at the offset specified in the square brackets. Means that give back the value retrieved from address of pointer plus the offset. The offset is always expressed in terms of type memory size not single bytes of memory. This is the so called pointers arithmetic. I.e. if we have a pointer to int
int *p;
and we access to a value as
int b = p[3];
means that the address in
p is added of 3 times the dimension of an
int then its fetched the value at that address, it iis equivalent to
((char *)p)+3*sizeof(int)
.
I hope now it's more clear why array and pointers can share some operators and constructs, but they remains two different things.Last for sake of completeness there was only one issue in the past about arrays related to the
& operator (address of). Because an array
is a memory reference, not an address stored, applying the operator formerly was an error. From one of the last ANSI standards (I'm not sure if C89 or C90) it is defined that the address operator applied to an array name give back again the address of the first element and is not an error. This makes definitively coincident the use of arrays names and pointers.
But if we clarified enough why syntax of them can be equivalent,
they still behaves differently: if you declare an array the compiler allocates the memory space to hold all elements, if you declare a pointer the compiler allocates only the memory necessary to hold a memory address. That's why applying
sizeof operator to an array give back the allocated memory for the whole array elements while applying it to a pointer give back the size in memory of a pointer.
So after declaring a pointer, and before to access data pointed by it, you must allocate memory and make the pointer point to it (i.e. using malloc). Or your program will blow up with a memory access exception...