I am trying to understand the special relationship that exists between array and pointers i.e. an array name without the brackets always points to the first element of the array.
On a Linux system, I get this with a C program:
char name[7] = "unique";
printf("\nAddress stored of name: %p", name);
printf("\nAddress stored of name: %s", name); //Conflict
printf("\nAddress of name[0]: %p", &name[0]);
//dereferencing the pointer
printf("\nValue of name[0]: %c", *name);
printf("\nValue of name[1]: %c", *(name+1));
The output is:
Address stored of name: 0xbff68131
Address stored of name: unique
Address of name[0]: 0xbff68131
Value of name[0]: u
Value of name[1]: n
I understand everything in the above output except the output of the line of code which as //Conflict. In other words, if name is equivalent to &name[0] as per the special relationship between array and pointers, then why simply changing the format specifier (from %p to %s) prints the actual value of the array. If that is truly the case, then does that mean name, &name[0] and *name are all equivalent?
I would at least expect it (//Conflict) to print some other (garbage?) value but not the actual value of the array.
%s
This tells printf to treat the argument as a pointer to a memory location which contains an array of characters, and prints each one until the \0 is encountered.
%p
This treats the arguement as a memory location and prints its value in hex, as you have seen.
What you are terming as "Conflict" is actually by far the more important use, and is the correct way to print c-strings.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With