I created three buffers and variables and copied each variable to the corresponding buffer.
Then I took the pointers from the buffer and printed it.
#include <stdlib.h>
#include <string.h>
int main() {
unsigned char a_buffer[sizeof(int)];
unsigned char b_buffer[sizeof(int)];
unsigned char c_buffer[sizeof(float)];
int a = 65500;
int b = 32000;
float c = 3.14;
int *aa = NULL;
int *bb = NULL;
float *cc = NULL;
memcpy(a_buffer, &a, sizeof(int));
memcpy(b_buffer, &b, sizeof(int));
memcpy(c_buffer, &c, sizeof(float));
aa = (int*) a_buffer;
bb = (int*) b_buffer;
cc = (float*) c_buffer;
printf("%i %i %f\n", *aa, *bb, *cc);
return 0;
}
Exit: 65500 32000 3.140000
Now I like to store these variables in one buffer and write this.
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
int main() {
unsigned char buffer[sizeof(int) + sizeof(int) + sizeof(float)];
unsigned char *buf_ptr = buffer;
int a = 65500;
int b = 32000;
float c = 3.14;
int *aa = NULL;
int *bb = NULL;
float *cc = NULL;
uint16_t cur = 0;
memcpy(buf_ptr + cur, &a, sizeof(int));
cur += sizeof(int);
memcpy(buf_ptr + cur, &b, sizeof(int));
cur += sizeof(int);
memcpy(buf_ptr + cur, &c, sizeof(float));
cur += sizeof(float);
cur = 0;
aa = (int*) buf_ptr + cur;
cur += sizeof(int);
bb = (int*) buf_ptr + cur;
cur += sizeof(int);
cc = (float*) buf_ptr + cur;
cur += sizeof(float);
printf("%i %i %f\n", *aa, *bb, *cc);
return 0;
}
Exit: 65500 2054246226 0.000000
The first variable is correct, the second is always changing, and the third is always zero.
What is the right way to do this?