0

I'm confused about how C stores in memory an array. From the example bellow the address of str1 is equal to its value. Whit this I was interpreting the result as: the memory address &str1 contains the value of the address itself. But this can not be the case because from other examples I saw the address of str1 contains the first value of the string, which in this case is "H".

So my question can be: where is the address of str1 stored?

#include <stdio.h>

int main(int argc, char const *argv[]) {
  char str1[] = "Hello World";
  printf("%d %d %c\n",&str1,str1,str1[0] );
  return 0;
}

1 Answers1

1

First of all, you must use %p format specifier to print an address (pointer).

That being said, quoting C11, chapter §6.3.2.1

Except when it is the operand of the sizeof operator, the _Alignof operator, or the unary & operator, or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue.

So, basically,

  printf("%p", str1);
  printf("%p", &str1[0]);

are the same.

Now, coming to the part of &str1, well, the type is different. It is of type char [<array size>].

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261