C change the value a void pointer represents

一曲冷凌霜 提交于 2021-02-11 12:41:48

问题


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"


回答1:


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.



来源:https://stackoverflow.com/questions/19581161/c-change-the-value-a-void-pointer-represents

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!