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

0


a source to share


4 answers


Like this:

*((int*) memp) = 250;

      



This is to say that even if memp

is a pointer to characters, I want you to treat it as a pointer to integers and put that integer where it points. "

+2


a source


Do you consider using union as in:

union mem_with_size {
  int   size;
  uchar mem[32*1024];
};

      



Then you don't need to worry about casting. (You still have to worry about byte ordering, of course, but that's a different issue.)

+2


a source


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.

+1


a source


Insert pointer to int

, not unsigned char

again!

int * memp = (int *)mem;
* memp = 250; //An example of size I want to assign.

      

0


a source







All Articles