1
#include <stdio.h>

int main()
{   
    char a[8];    
    printf("%d\n",a) ;    
    return 0;    
}

For the above code the output was this :- 2686744

What is the reason behind this output? I found that the output doesn't depend on the content of the array, but on the size of the array.I just want the explanation.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Farhan Hasin
  • 55
  • 1
  • 6

2 Answers2

1

You are printing the address of the array as an integer.

If you compile with -Wall to enable warnings your compiler should complain about that.

Doug Currie
  • 40,708
  • 1
  • 95
  • 119
1
char a[8];    
printf("%d\n",a);

This code has undefined behavior.

The array expression a is implicitly converted to a char* value, equivalent to &a[0]. That value is then passed to printf -- but since the %d format requires an int argument, the behavior is undefined.

If int and char* happen to have the same size, and if they're passed as function arguments using the same mechanism, then it will likely print a decimal representation of the address of (the initial element of) the array.

But don't do that. If you want to print the address:

printf("%p\n", (void*)a);
Keith Thompson
  • 254,901
  • 44
  • 429
  • 631