How to assign an int string and pass that int printf prints the string correctly?

Why does it work? (that is, how passing an int to printf() prints a string)

 #include<stdio.h> int main() { int n="String"; printf("%s",n); return 0; } 

warning: initialization makes an integer from a pointer without a cast [enabled by default]
int n = "String"; warning: format '% s expects an argument of type char *, but argument 2 is of type' int [-Wformat =]
E ("% s", n);

Output: String

: gcc 4.8.5

+5
source share
4 answers

In your code

  int n="String"; //conversion of pointer to integer 

highly dependent on the implementation of note 1

and

  printf("%s",n); //passing incompatible type of argument 

causes undefined behavior . note 2 Do not do this .

The moral of the story: Warnings exist for some reason, pay attention to them.


Note 1:

Citation C11 , chapter ยง6.3.2.3

Any type of pointer can be converted to an integer type. Except as noted above, the result is determined by implementation. If the result cannot be represented in an integer type, the behavior is undefined. [....]

Note 2:

chapter ยง7.21.6.1

[....] If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.

and for argument type for %s format specifier with printf()

s If there is no modifier of length l , the argument should be a pointer to the starting element of the array of character type. [...]

+8
source

Your program behavior is undefined.

Essentially, you assign const char* to int , and printf converts it back. But consider this an absolute coincidence: you are not allowed to use such unrelated types.

C gives you the ability to shoot in the foot.

+5
source

int type can store 4 bytes on most modern computers (from -2147483647 to 2147483647)

This means that it "can" also "store SOME address, only the problem is that your address is larger than 2147483647, it will cause overflow and you will not be able to get the address (which is very bad for your program obviously)

An address is a memory number. Pointers are used to store addresses, they are larger (8 bytes on 64-bit systems, 4 bytes on 32-bit systems), and they are also unsigned (only positive)

which means that if you act on int n="String"; if the address "String" is under the number 2147483647, this will not cause problems, and the code will be launched (DO NOT SHOULD THIS)

http://www.tutorialspoint.com/c_standard_library/limits_h.htm

Now, if you think about it, you can guess why there is a 4 GB limit on 32-bit systems

(sorry for possible English errors, I'm French)

+1
source

Compiling with options like -Wall -Wextra -Werror -Wint-to-pointer-cast -pedantic (GCC) will show you very quickly that you should not rely on this behavior.

0
source

All Articles