Storing a string in a integer variable in C

  • A+
Category:Languages
#include <stdio.h> int main() {     int a = "Hi";     char b = 'F';      int c = a + b;      printf("%d",a);        /* (1) */     printf("%d",c);        /* (2) */  } 

How come the output of the instruction (1) is 18537? How is it storing the value in terms of ANSI standard

Instruction (2) is clear since we are basically adding 70 to 18537 which gives 18607

Can some one elaborate on how the value is being stored in the integer variable in terms of string ?

 


Compiler warnings for the win!

$ cc -Wall -Wextra e.c  e.c: In function ‘main’: e.c:4:13: warning: initialization makes integer from pointer without a cast [-Wint-conversion]      int a = "Hi";              ^~~~ 

You assign the memory address of the string literal to the variable a. Well, in many cases you do. However, this is not guaranteed and there are potential problems involved with this. For example, an int may not be enough to hold the whole address.

It could be worth pointing out that this is not valid C code, so do not do this. According to https://port70.net/~nsz/c/c11/n1570.html#6.5.16.1p1 (Thank you @Lundin for providing the link):

One of the following shall hold:112)

  • the left operand has atomic, qualified, or unqualified arithmetic type, and the right has arithmetic type;
  • the left operand has an atomic, qualified, or unqualified version of a structure or union type compatible with the type of the right;
  • the left operand has atomic, qualified, or unqualified pointer type, and (considering the type the left operand would have after lvalue conversion) both operands are pointers to qualified or unqualified versions of compatible types, and the type pointed to by the left has all the qualifiers of the type pointed to by the right;
  • the left operand has atomic, qualified, or unqualified pointer type, and (considering the type the left operand would have after lvalue conversion) one operand is a pointer to an object type, and the other is a pointer to a qualified or unqualified version of void, and the type pointed to by the left has all the qualifiers of the type pointed to by the right;
  • the left operand is an atomic, qualified, or unqualified pointer, and the right is a null pointer constant; or
  • the left operand has type atomic, qualified, or unqualified _Bool, and the right is a pointer.

See Lundin's answer for how to force the compiler to not accept invalid code.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: