gpt4 book ai didi

c - 从 Void * 参数中获取整数数组

转载 作者:太空宇宙 更新时间:2023-11-03 23:25:16 24 4
gpt4 key购买 nike

给定一个具有参数 void *X 的函数,我如何将整数数组 x 作为参数传递,并将该函数中的局部整数变量 y 设置为 X?

    ...

int x[2];

x[0] = 1;
x[1] = 2;

foo((void*)x);

...
/*foo function:*/

void foo(void *X) {
//I want a local variable y (integer array) to be set to X

}

最佳答案

你只需要声明一个int *指针,并将void *指针赋值给它,就这么简单

void foo(void *X) {
int *x;
x = X;
if (x == NULL) /* prevent NULL dereference */
return;
}

f((void *)x); 是不需要的,你可以只使用 f(x);

此外,根据您的需要,您可能希望创建一个结构并将指针传递给该结构,该结构包含您的数组可以容纳的项目数,这样会更安全,并且易于维护。

这是引用自 C11 草案 1570

§ 6.3.2.3 Poitners

  1. A pointer to void may be converted to or from a pointer to any object type. A pointer to any object type may be converted to a pointer to void and back again; the result shall compare equal to the original pointer.

关于c - 从 Void * 参数中获取整数数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28663603/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com