Home > Software design >  In C, what does it actually do when you input a string but print it out as integer?
In C, what does it actually do when you input a string but print it out as integer?

Time:09-16

In this code below, I input a string but have it converted to integer and print it out.

int main ()
{
   int v6[4];
   printf ("Enter a string: ");
   int i = scanf ("%s",v6);  
   printf ("%d ",v6[0]);
  
  return 0;
}

Output:

Enter a string: tom
7171956

What did it actually do?

CodePudding user response:

Take your answer

7171956

convert it to hex

0x6d6f74

Check an ascii table

mot

You have filled the memory with the the ascii representation of tom then you read it as an integer, taking byte order into account.

CodePudding user response:

This is probably happening here: (assuming int is a 32 bit type on your platform):

int v6[4] takes 16 bytes in memory.

After your scanf with tom as input, the first n bytes of v6 look like this: (x being an undetermined value).

 ----- ----- ----- ----- ----- ----- ----- ----- ----
| 't' | 'o' | 'm' |  0  |  x  |  x  |  x  |  x  | ...
 ----- ----- ----- ----- ----- ----- ----- ----- ----

The same thing in hexadécimal (0x74 being the ASCII code for the letter 't' etc.):

 ----- ----- ----- ----- ----- ----- ----- ----- ----
| 74  |  6F |  6D |  0  |  x  |  x  |  x  |  x  | ...
 ----- ----- ----- ----- ----- ----- ----- ----- ----

The value 0x6d6f74 (which is v6[0]) converted to decimal is 7171956.

Be aware that on a big endian (google that term) architeture v[0] would be 0x746f6d00.

But don't do these kind of things, it's undefined behaviour (also google that).

  • Related