Search code examples
arrayscstructure

Trying to print structure variable without dot operator


I am trying to print a structure variable simply without any dot or arrow operator.

#include<stdio.h>
int main()
{
    struct test{
        char A[10];
        float b;
    }obj = {"Testing",3.14};

    printf("%u\n",&obj);
    printf("%u\n",&obj.A);
    printf("%u\n",obj);
}

OUTPUT

6422288
6422288
1953719636

See the third printf statement. I am simply trying to print the value of obj. Now i know it is something i am not supposed to do but i was just curious. The above two statements are simply printing the start address of the structure variable(assuming there is no pre structure padding involved here) but i am unable to understand what is happening in case 3. If it was an array of structure than simply writing obj would provide the base address of that array but what is the logic here ?


Solution

  • Based on the output, I know that your machine is little endian and has 4 byte ints.

    In ASCII "Testing" is { 0x54, 0x65, 0x73, 0x74 ... }. When you tell printf to use the %u format specifier for unsigned int, it looks at the first 4 bytes of the "value" of obj. Interpretted as little endian, this is 0x74736554, which in base 10 is 1953719636, the value you see output.