edited by
483 views
1 votes
1 votes
int main(){
    int a[5]={1,2,3,4,5};
    char *str="hello";
    printf("%p %p",a,&a);
    printf("%p %p",str,&str);
}



Why in $1$st printf , both the outputs are same($a$,&$a$)

And in $2$nd printf ,both the outputs are different(str,&str)

please help!

edited by

1 Answer

Best answer
3 votes
3 votes

  • $a$ is an array .
  • $a$ decays to the address of the first element of a[] , i.e. a decays to a pointer of type int*. (pointer to an integer)
  • &$a$ is also a pointer having the same numerical value of &$a$[$0$], but &$a$ has different type , int (*) [5]
  • This difference comes into picture when we do the pointer arithmetic as shown in the above image.
  • str and string literal "hello" has different storage location in memory.
  • str is a pointer of char* type and stores the starting address of "hello"
  • But str has its own address ,i.e.  &str , type is pointer to a character pointer.
  • Some pointer arithmetic is also shown in above image.
selected by

Related questions

0 votes
0 votes
1 answer
1
Debargha Mitra Roy asked 2 days ago
42 views
#include <stdio.h int main() { int a[3] = {1, 3, 5, 7, 9, 11}; int *ptr = a[0]; ptr += sizeof(int); printf("%d", *ptr); return 0; }(Assume size of int to be $2$ bytes.)T...