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?

3
  • 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. Commented Mar 17, 2017 at 8: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); Commented Mar 17, 2017 at 8:32
  • Correct format specifier to print pointer (address)? Commented Mar 17, 2017 at 9:19

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Note, some compilers warn for format specifier mismatches. E.g. recent versions of gcc and clang with -Wall
@M.M.: Many nonrecent versions did, too. It was certainly present in 2.95 (c. 1999), and i think it was already old.
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.

4 Comments

constraint violation...can you please elaborate?
Thanks, just downvoted, as you're absolutely wrong. :)
@SouravGhosh hello sir, I have changed my answer.
%d is not a valid conversion specifier for character pointers it is not for any pointer, as a matter of fact.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.