1

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"

Community
  • 1
  • 1
Vince
  • 3,979
  • 10
  • 41
  • 69

1 Answers1

8

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.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • oh, I was fighting with tutorials on pointers and searching in forums and the answer what that basic. Thx. – Vince Oct 25 '13 at 04:44
  • Also, don't forget, pointer arithmetic on void pointers isn't strictly valid C. – tangrs Oct 25 '13 at 04:50
  • actually, I have no clue about that. what would be the valid way to get the pointer position to the right place ? – Vince Oct 25 '13 at 05:01
  • Don't you see how I did it in the answer? – Barmar Oct 25 '13 at 05:03
  • I did, but I did not understand what the cast to char* does (since position is a void*). Should I ask a new question or is there a simple answer that would fit these comments ? – Vince Oct 25 '13 at 06:24
  • Casting to `char*` allows you to do arithmetic on the pointer, since the size of a char is known (it's defined to be 1), and `size_t` represents sizes as multiples of this. `void` doesn't have a size because it represents an unspecified type, so you can't do arithmetic on these pointers. – Barmar Oct 25 '13 at 06:36
  • That clarifies ! Thx a lot. – Vince Oct 25 '13 at 06:39