Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Well for a quick sum up:

An array is like a constant pointer, it's always pointing at the first element of the the array. To try to point it at something else is an error.

    array[2] 
is short for

    *(array + 2*sizeof(<type of array>)) 
which takes the address of the first element and adds the appropriate number of bytes to it in order to access the requested element, then it dereferences the "pointer" and you get the value of the element.

If this isn't 100% correct, please let me know.



As RegEx implies, pointer arithmetic implicitly includes the sizeof(<array type>) term, i.e. given

  int* array;
then

  array + 1
points to the next int, not the next byte. And so array[2] == *(array + 2). (The fact that addition commutes means that using 2[array] instead is valid and works in C.)


From the C standard:

> The definition of the subscript operator [] is that E1[E2] is identical to (((E1)+(E2))).

So array[2] == (array + 2)


Just as with pointer arithmetic (because that's what this actually is) you don't multiply by the size of its elements. This:

  array[2]
is the same as this:

  *(array + 2)
The compiler knows what the type of data the pointer refers to and can produce the byte offset itself. Also:

  "...it's always pointing at the first element of the the array"
Eh... an array can degrade into a pointer when needed, but what does the following produce?

  char arr[10];
  ??? x = &arr;
Is "x" a pointer to pointer to char? From your assessment it would seem so, but in reality the type of "x" is

  char (*)[10]
i.e., pointer to array of char 10. An array is an array, and arrays can degrade into pointer types.


Additionally, (as you know, but merely pointing out for the curious), `sizeof arr` returns the size of arr in bytes, not the size of a pointer to the first element of arr.


  > ??? x = &arr;
Does this compile? I thought an array was treated like a constant pointer, inexistent in memory so you cannot take its address, increment it, or attribute it another value. Although the point made by RegEx about sizeof, which I didn't remember, convinced me that an array is not actually a constant pointer.

To make my thoughts clear, if arr is equivalent to &arr[0], then wouldn't &arr be equivalent to &&arr[0]?




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: