Domanda

This is a follow up to this question: Having a function change the value a pointer represents in C

As an exercise, I am trying to make a generic function that changes a value in an array of undetermined type. I guess it should look like that.

void set_value(void * data, void * value, size_t size, int index){
    void * position = data + index*size;
    *position = *value;
}

Of course that does not compile, *position = *value do not use the information of the size of value (here was assume both data and value point to smthg of size_t size).

What I am trying to say to my program is : "take the chunk of memory of size pointed to by value and copy it at the address pointed to by position"

È stato utile?

Soluzione

Use memcpy().

void set_value(void * data, void * value, size_t size, int index){
    void * position = (char*)data + index*size;
    memcpy(position, value, size);
}

Note also that arithmetic on void pointers is not valid C, although it may be allowed as a compiler extension. You should cast to char* first.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top