// `str1` is an _array of char_
char str1[] = "Hello";
What's the difference between a name array and the (address of the) first element of the array in C?
An array is several elements of the same type. The (address of the) first element is an address.
I've been told that the name array is basically just a reference to the first element of the array ...
In some contexts, they appear the same, yet that is a result of a conversion. 1st line: the array str1
is passed to printf()
and in this context, the array is converted. str1
is converted from an array to the address and type of the first element.
printf("%s\n", str1); // Prints "Hello\n"
2nd line: The address of the first array element is passed.
printf("%s\n", &str1[0]); // Prints "Hello\n"
Unsurprisingly, they print the same.
In this context, you will certainly see a difference.
printf("size: %zu\n", sizeof str1); // Prints 6
printf("size: %zu\n", sizeof &str1[0]);// Size of a char * pointer
we can see that both str1
and str1[0]
share the same memory address
printf("%d %d\n", &str1, &str1[0]);
This line of exploration can mis-lead. &str1
and &str1[0]
are both addresses to the same memory location but have different types: address of a array 6 of char vs address of a char
.
As very different types they may even print different address encodings as a addresses may have many representations. (This is uncommon though).
Note: using "%d"
to print object pointers is not well defined, use "%p"
after a (void *)
cast.
printf("%p %p\n", (void *) &str1, (void *) &str1[0]);