Are pointers and arrays equivalent in C?
eli.thegreenplace.net
eli.thegreenplace.net
a[b] == *(a + b);
The surprising consequence of this is that the following is legal: int foo[] = { 1, 2, 3 };
int bar = 2[foo]; /* yes, this evaluates to 3 */
because *(2 + foo)
is legal, and + is commutative. This works for both pointers and arrays. I haven't worked out a practical use, though I suspect the C++ metaprogramming crowd might have. Obviously the equivalence only holds on the native types in C++ as [], + and * can each be separately overloaded.http://www.dreamincode.net/forums/index.php?showtopic=38102
It makes perfect sense when you consider the semantics of [], but I never would have thought to try it myself!
``pointer arithmetic and array indexing [that] are equivalent in C, pointers and arrays are different.''
Array names are immutable. Pointer values may be mutable.
However, let's ignore that and consider "int a[10]; int * const p(a);"
sizeof(a) is the size of the array named a or 4 * sizeof(int). sizeof(p) is the size of the pointer named p.
i.e. void f(int a[4]) { printf("%d", sizeof(a)); } int main() { int b[4]; f(b); } ... yields "4" (on my 32-bit machine)
So I guess it depends on what you mean by "equivalent."
This was very confusing to me when I learned C because it's one of those undefined behaviours that appears to work properly in trivial programs (at least with the compiler I was using).
Variables have block scope, but storage duration need not. If you return a pointer to a block of memory allocated within a function, that is not undefined behaviour. If you return a pointer an array declared within the function that is (if you return a pointer to a static array declared within a function that is not). That's the contrast I was trying to point out.
array[-1]
is not valid, while pointer[-1]
can be valid, such as if it points to the middle of a data set. struct {
char somechar;
char somearray[7];
} foo = {'E', "xample"};
printf("%c\n", foo.somearray[-1]); // prints 'E'
// (depending on your compiler and the
// struct-packing directions you gave it)I don't think I was trust this piece of code in a commercial application. There is too much variation which would make it unreliable across platforms and compilers.
> Here’s a quote from Expert C Programming:
>
> There is one difference between an array name and a
> pointer that must be kept in mind. A pointer is a
> variable, so pa=a and pa++ are legal. But an array
> name is not a variable; constructions like a=pa and
> a++ are illegal.
That's deep.