-3
#include <stdio.h>

int main(void){
    int a = 6;
    int *pa;
    pa = &a;
    printf("%d\n",*pa); //6
    printf("%d\n",pa); //1575619476
    printf("%s\n",pa); //nothing, a empty line

    char *s="test";
    printf("%d\n",s); //183013286
    printf("%s\n",s); //test
}

The code is simple, pa is a int typed pointer, we print pa, we get a memory address, we print *pa, we get its value;

But when it comes to a char typed pointer, things get interesting, it seems that printf can pick up the according type that it needs to output,

  • it needs a number, the "s" will give its address since it is a pointer;
  • it needs a string, the "s" will give the value to it.

OR does it means it is "s"'s responsible to give the proper value to printf? But it is not a object, how does the single value know some self-action?

what happened here?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Albert Gao
  • 3,653
  • 6
  • 40
  • 69

2 Answers2

3

In your code,

 printf("%d\n",pa);
 printf("%s\n",pa);

and

 printf("%d\n",s);

invokes undefined behavior as you're passing wrong type of arguments. Never rely on the output.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0

The field formatter %d means "convert the value of this variable to a decimal representation". So it always outputs a number, be it a normal value or the address carried by apointer.

The field formatter %s means "display the bytes from that address until you meet a null. So it outputs a string of characters of some length or raises a memory error if the variable is not holding an allowed address.