1

I've been reading this thread Store an int in a char array?

And I need to store the int in the array of chars.

So I read the previous thread and I tried to make my own demo. But it's not working, trying to figure out why not for a long time. Maybe you could give me some clue or ideas please?

#include <stdio.h>

int main(void) {

    char buffer[4];
    int y = 2200;
    buffer[0] = (y >> 0) & 0xff;
    buffer[1] = (y >> 8) & 0xff;
    buffer[2] = (y >> 16) & 0xff;
    buffer[3] = (y >> 24) & 0xff;

    int x = buffer[0];

    printf("%i = %i\n", y, x);
}

Output

gcc tmp.c && ./a.out
2200 = -104
Community
  • 1
  • 1
Jan Vorcak
  • 19,261
  • 14
  • 54
  • 90
  • 1
    This doesn't address your question directly, but be aware of the assumption you are making about the size of `int` on your system. – Alex Reynolds Oct 22 '12 at 23:54

2 Answers2

6
int x = buffer[0];

Copies the value of the char at buffer[0], implicitly converted to an int, into x. It does not interpret the first sizeof int bytes starting at buffer as an int, which is what you want (think of the evil ways that this behavior would subtly break in common scenarios, i.e., char c = 10; int x = c. Oops!).

Realize that buffer[n] doesn't return a memory address, it returns a char. To interpret sizeof int elements as one whole int just cast buffer to an int* first:

int x = *((int*)buffer);

And for an offset n (measured in ints, not chars):

int x = *((int*)buffer + n);

Also note that your code assumes sizeof int == 4, which is not guaranteed.

Ed S.
  • 122,712
  • 22
  • 185
  • 265
0

x = buffer[0] does not do what you wish. Try memcpy(&x,buffer,sizeof(x)). (You'll need to add #include <string.h>.)

lhf
  • 70,581
  • 9
  • 108
  • 149