-2

After initialising character array name and address refers to same. s[] is an array. so it decays to pointer s, &s should give the address of pointer s

#include <stdio.h>
int main()
{
   char s[]="Get Organised! learn C!";
   printf("%u %s\n",&s[2],&s[2] );
   printf("%u %s\n",s,s );  /* This line and below line is equivalent*/
   printf("%u %s\n",&s,&s ); /* Please Explain */
   printf("%u %s\n",s[2],s[2] );
   printf("%u %s\n",s[3],s[3] );
   return 0;
}

%u is just used to see what is going inside.

Jens
  • 69,818
  • 15
  • 125
  • 179
Saket Anand
  • 45
  • 1
  • 10

2 Answers2

1

Getting rid of undefined behaviour first:

int main() {
  char const string [] = "hello";
  printf("%p %p\n", (void *) string, (void *) &string);
  return 0;
}

You get (probably, that's target dependent) the same address printed here because the first expression is implicitly converted to a pointer to the first element of the array while the second is a pointer to the whole array (which most likely happens to start at its first element)

string == &(string[0]) // this is often called decaying

The type of the expression string (or more precisely the expression it decays to) is char const * whereas the type of &string is char const (*array)[6], so they're not "the same".

The reason that &string is not a pointer to a pointer is simple: The C standard explicitly forbids array expressions prefixed with the address of operator (&) (or inside an sizeof operator) to be implicitly converted to a pointer.

Daniel Jour
  • 15,896
  • 2
  • 36
  • 63
0

With the below, s is an array 100 of char. When is is passed to printf(), array s is converted to the value and type of the address of first element. So printf() is given a char *.

&s is the address of an array 100 of char. It has an equivalent value as s, yet a different type.

char s[100]="Whatever";
printf(some_format,s);
printf(some_format,&s);

To properly print addresses of variables, literals, cast to (void*) and use "%p". The print out typically lacks any description of the type of the variable.

printf("%p\n",(void*) s);
printf("%p\n",(void*) &s);

Output

0x28cbdc
0x28cbdc

To see an effect of the type difference:

printf("%zu\n",sizeof *(s));
printf("%zu\n",sizeof *(&s));

Output

1
100

@john bode also suggested this earlier.

Community
  • 1
  • 1
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256