Copy the variables into a single buffer and read them.

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() {

    // Buffers.
    unsigned char a_buffer[sizeof(int)];
    unsigned char b_buffer[sizeof(int)];
    unsigned char c_buffer[sizeof(float)];

    // Variables ressources.
    int a = 65500;
    int b = 32000;
    float c = 3.14;

    // Variables pointers.
    int *aa = NULL;
    int *bb = NULL;
    float *cc = NULL;

    /* Copy variables to buffer. */
    memcpy(a_buffer, &a, sizeof(int));
    memcpy(b_buffer, &b, sizeof(int));
    memcpy(c_buffer, &c, sizeof(float));

    /* Set pointers. */
    aa = (int*) a_buffer;
    bb = (int*) b_buffer;
    cc = (float*) c_buffer;

    // Print values.
    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() {

    // Buffer.
    unsigned char buffer[sizeof(int) + sizeof(int) + sizeof(float)];

    // Buffer pointer (first object).
    unsigned char *buf_ptr = buffer;

    // Variables ressources.
    int a = 65500;
    int b = 32000;
    float c = 3.14;

    // Variables pointers.
    int *aa = NULL;
    int *bb = NULL;
    float *cc = NULL;

    /* Copy variables to buffer. */
    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);

    /* Set pointers. */
    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);

    // Print values.
    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?

+4
source share
1 answer

Short answer: it looks like you are adding the wrong offset due to the type of pointer when executing the section aa = (int *)buf_ptr + cur.

Use aa = (int *)(buf_ptr + cur)instead (and accordingly for other pointer assignments).

, , , : https://ideone.com/64awsM

: buf_ptr (int *), , ( ). cur , , buf_ptr , buf_ptr[cur], int. cur=sizeof(int) (, 4 8), . buf_ptr char, , , .

, ( buf_ptr[0], , , ).

+2

Source: https://habr.com/ru/post/1610583/


All Articles