C 更改空指针表示的值 [英] C change the value a void pointer represents

查看:62
本文介绍了C 更改空指针表示的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是对这个问题的跟进:让函数更改指针在 C 中表示的值

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;
}

当然不编译,*position = *value 不使用 value 大小的信息(这里假设 data 和 value 都指向 size_t 大小的 smthg).

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).

我想对我的程序说的是:"取value所指向的size内存块,复制到position所指向的地址处"

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"

推荐答案

使用 memcpy().

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

还要注意,void 指针上的算术不是有效的 C,尽管它可能被允许作为编译器扩展.您应该先转换为 char*.

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.

这篇关于C 更改空指针表示的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆