Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/62.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/delphi/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将struct作为参数传递以代替void*_C_Function_Struct_Void Pointers - Fatal编程技术网

将struct作为参数传递以代替void*

将struct作为参数传递以代替void*,c,function,struct,void-pointers,C,Function,Struct,Void Pointers,我有一个接受void*作为参数的函数,但我想把它当作一个结构来使用 typedef struct struct1 { int val; } struct2; void func1(void* struct3) { printf("%d",struct3->val); } 例如,如果我有一个.h文件,其中函数定义为 typedef void* parameter1; void func1(parameter1 p1); 我想在该函数中使用结构作为参数,而不在.h文件中声

我有一个接受void*作为参数的函数,但我想把它当作一个结构来使用

typedef struct struct1
{
    int val;
} struct2;

void func1(void* struct3)
{
    printf("%d",struct3->val);
}
例如,如果我有一个.h文件,其中函数定义为

typedef void* parameter1;
void func1(parameter1 p1);

我想在该函数中使用结构作为参数,而不在.h文件中声明结构。

感谢@i486提到的答案
printf(“%d”)((struct2*)struct3)->val)
,这就是我想要的答案

在标题中,将结构类型声明为不完整类型。例如:

typedef struct struct1 struct1;
extern void func1(struct1 *p1);
或:

您可以混合使用'n'match
extern
或'not'和
typedef
vs
struct tag

在实现代码(如果有多个源文件实现对该类型的支持,则为实现头)中,包括公共头并定义结构类型:

struct struct1
{
    …private details…
};
在C11及更高版本中,您可以重复
typedef
,只要它引用相同的类型;在早期版本的C中,您无法做到这一点


这种方法的优点是,客户机代码被迫使用您的函数,因为它们不知道结构的内部结构,但它们得到了类型安全性的度量。特别是,不能将随机结构指针传递给此函数。如果所有内容都采用
void*
,则可能会向函数传递错误的结构类型,因为所有
void
指针看起来都很相似。这既不友好也没有必要。

请不要使用空指针,。它通常以tears结尾。您不能对空指针使用
->
,您需要一个结构指针,或者至少是一个cast。@在函数定义中的任何情况下,您都必须知道参数的实际类型。
printf(“%d”)((struct2*)struct3)->val)
。此外,关于结构和类型别名(
typedef
),您可以使结构名称和类型别名相同。结构名称存在于它们自己的名称空间中,因此您可以这样做,例如
typedef struct foo{…}foo;
在带有运算符(&)地址的用户名字对象之前工作与
@
符号一样。例如@i486.:)你可能一直在寻找这个,但它肯定不是你需要的。这就是XY问题的解决方案和desaster的配方。为什么不直接使用正确的参数类型?
struct struct1
{
    …private details…
};