What's happening here? (pointers in C)

This paragraph is pretty much entirely false. &ptrs and &ptrs[0] may have different values (seen as void*s)

For my own correction and understanding, can you provide a counter-example to:

int main() {
  int a[2] = {1, 2};
  printf("%p\n", a);
  printf("%p\n", &a);
  printf("%p\n", &a[0]);
  return 0;
}

...for which the value of ptrs, &ptrs and &ptrs[0] are shown to contain different values? They certainly semantically represent different things, though have identical values in the end. As I understand it, this is part of the specification as set by K&R (and that understanding may be wrong/out-of-date). You may certainly write a compiler that does something else, but if you do, you have written something which isn't fundamentally a c-compiler.

And again: an array is not a static reference, an array is a contiguous sequence of objects.

I'm not sure I agree, but maybe that's just the compiler author in me. I may also have tripped over my words - which wouldn't be unheard of in my case ;P. When I say array, I intended to specifically mean the four characters: ptrs in the source code. I don't think you can claim that this is a contiguous sequence of objects. Sure, it represents what will eventually become a contiguous sequence of objects, but before the compiler is done with its job, ptrs is really just a label, just like any other variable.

However, unlike any other variable, there are some unique semantics the compiler associates with this particular label. Those semantics are what I had intended to point out (and maybe I did a bad job, you seem to think I did). Specifically, in terms of a label that corresponds to an array, the semantics I was trying to demonstrate are:

  • The label's value represents the address of the first element in the array; always.
  • The & operator is treated specially. The compiler treats &ptrs as synonymous with ptrs.
  • The sizeof() operator is treated specially.
  • The label is considered static (or immutable). Given the static nature of the label, ptrs++ is illegal as it violates the label's immutable nature.

The main point I was trying to make is that people treat arrays and pointers as the same thing. 90% of the time they notice they can get away with it. They aren't the same thing, and you need to understand how. If I worded it awkwardly, I apologize.

/r/learnprogramming Thread Parent