4

I'm testing this code ,but why no error at all?

#include <stdio.h>

int main()
{

    int a = 1025;
    int *p;
    p = &a;

    // now I declare a char variable , 
    char *p0;
    p0 = (char*) p; // type casting
    printf("", sizeof(char));

    // is %d correct here ?????
    printf("Address = %d, value = %d\n", p0, *p0);

}

My question : Is %d correct here? since %d is integer not for character, why no error at all?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Lion Gordon
  • 87
  • 1
  • 6
  • 1
    Actually the problem is the first `%d` where you are passing an address: you should use `%p`. `printf("Address = %p, value = %d\n", (void *)p0, *p0);` For the second one `char` value is just promoted to `int`. – LPs Mar 17 '17 at 08:22
  • Moreover errors/warnings depends also on how you are compiling your code: using `gcc -Wall -Wextra -pedantic-errors test.c -o test -std=c11 -g`, you have `warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘char *’ [-Wformat=] printf("Address = %d, value = %d\n", p0, *p0);` – LPs Mar 17 '17 at 08:32
  • [Correct format specifier to print pointer (address)?](http://stackoverflow.com/q/9053658/995714) – phuclv Mar 17 '17 at 09:19

2 Answers2

4

In your case

 p0 = (char*) p;

is valid, because char * can be used to access any other types. Related, quoting C11, chapter §6.3.2.3

[...] When a pointer to an object is converted to a pointer to a character type, the result points to the lowest addressed byte of the object. Successive increments of the result, up to the size of the object, yield pointers to the remaining bytes of the object.

However, in case of

    printf("Address = %d, value = %d\n", p0, *p0);

causes undefined behavior, as you're passing a pointer (p0) to %d (Look at the first "pair" of conversion specifier and corresponding argument). You should use %p and cast the argument to void *, something like

   printf("Address = %p, value = %d\n", (void *)p0, *p0);

Then, to answer

No error at all, why?

because the issue is not with the syntax or any constraint violation which the compiler is supposed to complain about. It's purely mis-use of given power. :)

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • Note, some compilers warn for format specifier mismatches. E.g. recent versions of gcc and clang with `-Wall` – M.M Mar 17 '17 at 08:36
  • @M.M.: Many nonrecent versions did, too. It was certainly present in 2.95 (c. 1999), and i think it was already old. – rici Mar 17 '17 at 09:17
1

It's undefined behaviour because p0 is a char*, the code printf("Address = %d, value = %d\n", p0, *p0) and %d is not a valid conversion specifier for character pointers.

msc
  • 33,420
  • 29
  • 119
  • 214