Tanay PrabhuDesai
Tanay PrabhuDesai

Reputation: 65

C programming %d { printf("%d"); }

The program is as follows:

#include<stdio.h>
int main()
{
   int a[7]={1,2,3,4};
   printf("%d%d%d%d%d",(*a),*(&*a),a[*a*0],*a);
   return 0;
}

The Output on codepad.org is as follows: 11110

The Output on ideone.com is as follows: 1111-1074526944 where -1074526944 keeps varying every execution

I executed it on my personal gcc output is: 11110 i dont have the latest gcc

In the printf(); statement i am not concerned about the first four %d's because its totally obvious. its the fifth %d i am concerned about. Why does it give such an output?

Upvotes: 1

Views: 544

Answers (1)

Flavius
Flavius

Reputation: 13816

It tries to access whatever data happened to be on the stack of the call to printf() at the offset where a supposed "fifth parameter" would be, which your call to the function obviously has not provided.

  • To get a feel for it, learn how to write variadic functions.
  • To really understand it, you'd have to learn assembly.
  • To avoid such programming mistakes, use the -Wall parameter, which would have told you:
$ gcc -Wall main.c 
main.c: In function ‘main’:
main.c:5:4: warning: format ‘%d’ expects a matching ‘int’ argument [-Wformat]

Upvotes: 8

Related Questions