Home > Enterprise >  How does an int variable casted to char* print a string?
How does an int variable casted to char* print a string?

Time:09-30

I'm having a hard time wrapping my head around how a line of this code is working.

#include <stdio.h>
#define NUM 6513249

int main()
{
        int a = NUM;
        char * pt = (char *) &a;
        printf("a is: %d\n", a);

        //Line I don't understand (I think)
        printf("string is: %s\n", pt)

        return 0;
}

Expected and actual output:

a is: 6513249
string is: abc

To be clear, this program is supposed to print this string, I just don't really understand fully how it is doing it.

My current understanding is that when you cast an address of a variable with integer type to a pointer with char pointer type, the pointer points to only the first memory address that the int variable was stored in.

What I don't understand is how the pointer, which as I understand will pass the first memory address of a, is being converted to to the string "abc". Is there a flaw in my understandings of casting and printing pointers?

CodePudding user response:

The number 6513249 has the hex value 00636261. On a little-endian architecture, the bytes are stored least-significant first, so this is stored in memory as

61 62 63 00

61 is the ASCII code for a, 62 is the ASCII code for b, and 63 is the ASCII code for c. So this is the same memory contents as the string "abc" (00 is the null terminator). So if we treat the address of a as the beginning of a string (by casting &a to char*) and print it, we get abc.

This is totally unportable.

  • Related