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?