0

I read this: Difference between char a[]="string"; char *p="string";

But Consider below code: (I have hard coded to read the addresses: Just for trial purpose)

#include <stdio.h>

#define read(x,y) *((y*) x)

int main()
{
const char name[]="Andrew";
printf("Printing name : %p\n",name);
printf("Printing &name : %p\n",&name);
printf("At address 0x22ac39:%c\n",read(0x22ac39,char));
printf("At address 0x22ac3a:%c\n",read(0x22ac3a,char));
printf("At address 0x22ac3b:%c\n",read(0x22ac3b,char));
printf("At address 0x22ac3c:%c\n",read(0x22ac3c,char));
printf("At address 0x22ac3d:%c\n",read(0x22ac3d,char));

const char* add="University Of Glasgow";
printf("Printing add :  %p\n",add);
printf("Printing &add : %p\n",&add);
printf("At address 0x402121:%c\n",read(0x402121,char));
printf("At address 0x402122:%c\n",read(0x402122,char));
printf("At address 0x402123:%c\n",read(0x402123,char));
printf("At address 0x402124:%c\n",read(0x402124,char));
printf("At address 0x402125:%c\n",read(0x402125,char));


return 0;
}

The output shows:

$ ./memory.exe
Printing name : 0x22ac39
Printing &name : 0x22ac39
At address 0x22ac39:A
At address 0x22ac3a:n
At address 0x22ac3b:d
At address 0x22ac3c:r
At address 0x22ac3d:e
Printing add :  0x402121
Printing &add : 0x22ac34
At address 0x402121:U
At address 0x402122:n
At address 0x402123:i
At address 0x402124:v
At address 0x402125:e

Rest All fine but not able to grasp how below two statements, showing the same content?

printf("Printing name : %p\n",name);
printf("Printing &name : %p\n",&name);
Community
  • 1
  • 1
Gaurav K
  • 2,864
  • 9
  • 39
  • 68
  • 2
    You may want to read http://stackoverflow.com/questions/2528318/how-come-an-arrays-address-is-equal-to-its-value-in-c, especially Jerry's answer. May I add that you could have done that before asking that question? The link popped up as the first hit when I googled "c address array". – Peter - Reinstate Monica Jun 05 '14 at 12:10

1 Answers1

0

char* is a (runtime stored) pointer to a char (or an array of chars), meanwhile char[] is an array of chars itself and there is no pointer stored at runtime.

Thats why in case of char[] the address of the first char and the adress of the array instance itself are the same.

Ole Dittmann
  • 1,764
  • 1
  • 14
  • 22
  • One might add (I just learned that from the question I cited above) that the array usually decays to a pointer to its first element (i.e. your char *), e.g. as a parameter to printf in `printf("Printing name : %p\n",name);`. One of the few instances in C where an array does not decay is the sizeof operator and the, you guess it, & operator, which yields the address of the array object itself. Of course that address is numerically the same as the address of the array's first element, but incrementing it adds numerically sizeof(arr) to the address. – Peter - Reinstate Monica Jun 05 '14 at 12:15