-1

This is struct node with 2 variables.

typedef struct{
    int a;
    int b;
}node;

Inserting the values into vector of the node type.

    vector <node> nv;
    node n;

    n.a = 10;
    n.b = 20;
    nv.push_back(n);

    n.a = 100;
    n.b = 200;
    nv.push_back(n);

Copying the vector to a void pointer.

    void *ptr = malloc(4096);
    memcpy((char*)ptr,&nv,sizeof(node)*2);

Reading the values from the void pointer

    node *temp;

    temp = (node*)malloc(sizeof(node));

    int offset = 0;
    i = 0;
    while(i<n){
        memcpy((node*)temp,(char*)ptr + offset, sizeof(node));
        cout<<"a - "<<temp->a<<" b -"<<temp->b<<endl;
        offset += sizeof(node);
        i++;
    }

I am printing the values of a and b. But they are incorrect and contains random numbers. I am sure that I am hitting the wrong memory location. But not sure where.

  • 4
    replace `&nv` with `nv.data()` – Iłya Bursov Oct 10 '18 at 15:28
  • 1
    Re: "Copying the vector to a void pointer" -- no, No, NO. The code copies the data to an array of bytes that's pointed to by a void pointer. Keep that distinction firmly in mind: a pointer **points at** something, and mostly you care about what it points at. – Pete Becker Oct 10 '18 at 16:10

1 Answers1

3

std::vector object is not an array object. The vector manages a dynamically allocated array. Just like your ptr isn't an array, but simply points to one.

Just like you musn't pass &ptr to malloc (as that would cause the data to be written over the pointer, not the pointed array), so too you musn't pass &nv (as that would cause the data to be read from vector which manages the array, rather than from the array which is being managed). Vector has a member function data which returns a pointer to the internal array.

eerorika
  • 232,697
  • 12
  • 197
  • 326
  • In that case, how can I write an object to a buffer? I tried static arrays, they work well. But in my case the problem is that I don't have the array size known in prior. – shreyas-badiger Oct 10 '18 at 19:08