Int in simulated memory uchar array
In C, in a Unix environment (Plan9), I have an array as memory.
uchar mem[32*1024];
I need this array to contain different fields like int (integer) to indicate the size of free and available memory. So I tried this:
uchar* memp=mem;
*memp=(int)250; //An example of size I want to assign.
I know the int size is 4, so I need to force with casting or something that the contents of the first four mem slots have the number 250 in this case, that's a big endian.
But the problem is I am trying to do what I explained, it doesn’t work. I am guessing there is a type conversion error. I hope I ask you, how can I get this mem [0] mem [3] to have the specified size, represented as int and no as uchar?
Thanks in advance
a source to share
As others have pointed out, you need to point to a pointer to int. You also need to make sure you take the pointer alignment: on many architectures, int must start at a memory location that is divisible by sizeof (int), and if you try to access a non-principal int, you get SIGBUS. On other architectures, it works, but slowly. In other cases, it works quickly.
A portable way to do this could be:
int x = 250;
memcpy(mem + offset, &x, sizeof(x));
Using unions can make it easier, however, so +1 to JamieH.