0

I have the following C code:

char arr[1];
printf("%p %p\n", &arr, arr);

The values of &arr and arr printed are always the same. This means that arr contains the location of itself.

If I dereference the array and write a value to it like so:

 *arr = 'a';

I expect it to overwrite the value in arr because arr points to itself.

But this doesn't happen. When I print the value of arr again:

printf("%p\n", arr);

It contains the same old value which is the location to itself.

Why doesn't arr get overwritten?

Edit: I tried the following links but none of them answered my question exactly:

What is array to pointer decay?

Does an Array variable point to itself?

  • `char[1]` is useless for holding strings. It's only able to hold a NUL, no actual string data. – tadman Jan 04 '23 at 16:19
  • 1
    "This means that arr contains the location of itself." No. No it does not. It means C is interpreting it as a pointer given the `%p` placeholder. – tadman Jan 04 '23 at 16:20
  • Tip: use a debugger to show what's actually happening in memory visually. – tadman Jan 04 '23 at 16:20
  • 1
    Also be aware that `*x` is strictly equivalent to `x[0]` or more generally: `*(x + y)` is strictly equivalent to `x[y]`. – Jabberwocky Jan 04 '23 at 16:22
  • Do not confuse an array with a pointer. An array is a composite variable. It's a collection of variables under the name of the array. A pointer is one variable that contains a memory address. The answer you linked explains how arrays and pointers can be used interchangeably, although they are different things. – giusti Jan 04 '23 at 16:42
  • @tadman, not useless. It can handle `""` which is a perfectly valid C-string. – tstanisl Jan 04 '23 at 22:06
  • @tstanisl Valid, but the use cases for that are extremely slim. I'm speaking in general terms, not theoreticals. – tadman Jan 04 '23 at 22:13

0 Answers0