2

I am trying to store int value in char array, and access it again to retrieve value later. here is what i tried, but it is not working as i am looking for.

char mem[50];
int* size = (int*)&mem[0];

char* isFree = (char*)&mem[4];

char *t = (char *)&mem[4];

Now I want to store 1234, and 'f' in the char array according to the order. (within first 5 bytes)

I am not allowed to use other variables, have to use char array.

int a = 1234;
int *size = &a;

above one is not allowed.

dhanushkac
  • 520
  • 2
  • 8
  • 25

3 Answers3

5

You have to use the type unsigned char to copy the memory or memcpy which does that for you. Aliasing a char array as an int is undefined in C.

store the value:

int value = 1234;
memcpy( mem, &value, sizeof(value) );

retrieve the value:

memcpy( &value, mem, sizeof(value) );

(The array mem must be large enough to hold the type int.)

this
  • 5,229
  • 1
  • 22
  • 51
  • thank you for answering my question. but this won't work. i am not allowed to use other variables than using array space. if not i can do this by using int a = 1234; size = (int *)&a; that's the issue – dhanushkac Nov 12 '15 at 16:16
  • Why not `char`? I see both mentioned in the description of strict aliasing [here](http://stackoverflow.com/a/99010/509868). Is there some additional rule I am not aware of? – anatolyg Nov 12 '15 at 16:16
  • 1
    @anatolyg Signed char could potentially have a value with trap representation if using one's complement or sign+magnitude, if I read the C11 Standard correctly: 6.2.6.2,p2. – this Nov 12 '15 at 16:25
2

You can use sprintf -

int size=1234;
char mem[50];
sprintf(mem,"%d",size);

Note- This will append null terminator.

ameyCU
  • 16,489
  • 2
  • 26
  • 41
1

I have tried another way and i got a solution. I am posting it as a help for others.

char mem[50];
int* size = (int*)&mem[0];
*size = 1234;

char* isFree = (char*)&mem[4];
*isFree = 'f';

char *t = (char *)&mem[4];

printf("%d\n",*(int*)&mem[0]);
printf("%c\n",*(char*)&mem[4]);

I assigned a pointer to a pointer. I worked. Thank you all for answering.

dhanushkac
  • 520
  • 2
  • 8
  • 25