Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

memcpy and pointers

Tags:

c

memcpy

I am confuse on how to read the pointers copied in an array using memcpy. Following is what I have tried, but does not work.

Basically, I have allocated block of memory in which I am copying pointers similar to array fashion, but during retrial it is not working. While this works with basic data types properly

I want to store anything in the element block, It can be either integers or pointers.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define INDEX(x)  ((char *)elements + (sizeof(int*) * (x)))
int size = 10;

void f2_int_ptr() {    
    int i = 0;
    void *elements = (void*)malloc(size * sizeof(int*));
    for ( i = 0; i < size; i++ ) { 
       int *v = ( int *) malloc ( sizeof(int));
       memcpy ( v, &i, sizeof ( int ));


       memcpy ( INDEX(i) , v,  sizeof (int*));
    }
    for ( i = 0; i < size; i++ ) { 
        int *v = (int*)0;
        memcpy ( v, INDEX(i), sizeof(int *));
        printf ( "%d\n", *v );
    }
}
void f1_int() {
    int i = 0;
    void *elements = (void*)malloc(size * sizeof(int));
    for ( i = 0; i < size; i++ ) { 
       memcpy ( INDEX(i) , &i,  sizeof (int));
    }
    for ( i = 0; i < size; i++ ) { 
        int v;
        memcpy ( &v, INDEX(i), sizeof ( int ));
        printf ( "%d\n", v );
    }
}
int main(){
    f1_int();
    f2_int_ptr();
    return 0;
}

In the above code f1_int works fine but f2_int_ptr does not work.

like image 606
Avinash Avatar asked Apr 01 '11 10:04

Avinash


1 Answers

f2_int_ptr() needs to become this:

void f2_int_ptr() {
    int i = 0;
    void *elements = malloc(size * sizeof(int*));

    for ( i = 0; i < size; i++ ) { 
       int *v = malloc ( sizeof(int));
       memcpy ( v, &i, sizeof ( int ));
       memcpy ( INDEX(i) , &v,  sizeof (int*));
    }

    for ( i = 0; i < size; i++ ) {
        int *v;
        memcpy ( &v, INDEX(i), sizeof(int *));
        printf ( "%d\n", *v );
    }
}

Note the subtle changes to the memcpy() arguments.

Note: I really, really, really, wouldn't write code like this! It's incredibly difficult to follow.

like image 157
Oliver Charlesworth Avatar answered Sep 28 '22 21:09

Oliver Charlesworth