0

Let's assume that we have a struct that has 4x 1-byte members. I want to use Xyz as a memory address and cast it as a 32bit pointer then I will assign values to it. By this, I would able to set all the byte members at once. This is just an example for my question, char, int, or set to 256 is just arbitrary examples.

 #include <stdio.h>

    struct temp{
        char abc;
        char def;
        char ghk;
        char lmn;
    }xyz;

    int main()
    {
        xyz = (struct temp){11,22,33,44};
        printf("Byte1 %d\r\n",xyz.abc);
        printf("Byte2 %d\r\n",xyz.def);
        printf("Byte3 %d\r\n",xyz.ghk);
        printf("Byte4 %d\r\n",xyz.lmn);    
        *((unsigned int*)xyz) = 256;
        printf("Byte1 %d\r\n",xyz.abc);
        printf("Byte2 %d\r\n",xyz.def);
        printf("Byte3 %d\r\n",xyz.ghk);
        printf("Byte4 %d\r\n",xyz.lmn); 
        return 0;
    }

Here I prepare a similar approach for the array which is working as expected ;

#include <stdio.h>

char mem[4];

int main()
{
    mem[0] = 49;
    mem[1] = 50;
    mem[2] = 51;
    mem[3] = 52;
    printf("Byte1 %d\r\n",mem[0]);
    printf("Byte2 %d\r\n",mem[1]);
    printf("Byte3 %d\r\n",mem[2]);
    printf("Byte4 %d\r\n",mem[3]);    
    *(int*)mem = 256;
    printf("Byte1 %d\r\n",mem[0]);
    printf("Byte2 %d\r\n",mem[1]);
    printf("Byte3 %d\r\n",mem[2]);
    printf("Byte4 %d\r\n",mem[3]);
    return 0;
}

How can I do the same thing that I did by an array by using struct?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335

1 Answers1

0

This:

*((unsigned int*)xyz) = 256;

Is a strict aliasing violation. This means you can't take a pointer to one type, cast it to another type, dereference the casted pointer, and expect things to work. The only exception is casting to a pointer to char * to read the individual bytes of some other type.

What you can do however is use a union. It is permitted to write to one member of a union and read from another to reinterpret the bytes as a different type. For example:

union u {
    int i;
    struct {
        char c1;
        char c2;
        char c3;
        char c4;
    } s;
};

...

union u u1;
u1.i = 256;
printf("byte1=%02x\n", u1.c1);
printf("byte2=%02x\n", u1.c2);
printf("byte3=%02x\n", u1.c3);
printf("byte4=%02x\n", u1.c4);
dbush
  • 205,898
  • 23
  • 218
  • 273