Lion Gordon
Lion Gordon

Reputation: 99

No error at all, why?

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?

Upvotes: 4

Views: 77

Answers (2)

msc
msc

Reputation: 34688

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.

Upvotes: 1

Sourav Ghosh
Sourav Ghosh

Reputation: 134396

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. :)

Upvotes: 4

Related Questions