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
Copies the value of the
charatbuffer[0], implicitly converted to an int, intox. It does not interpret the firstsizeof intbytes starting atbufferas anint, 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 achar. To interpretsizeof intelements as one wholeintjust castbufferto anint*first:And for an offset
n(measured inints, notchars):Also note that your code assumes
sizeof int == 4, which is not guaranteed.