gpt4 book ai didi

c - 在其字段中声明指向结构的指针

转载 作者:行者123 更新时间:2023-11-30 18:51:49 25 4
gpt4 key购买 nike

我需要对结构指针进行 typedef,然后在其字段中使用新类型。

我的意思是,而不是这样做:

struct app 
{
char *data;
struct app *ptr;
}

我需要在某处输入 typedef app* appPtr;然后像这样使用它:

struct app 
{
char *data;
appPtr ptr;
}

我怎样才能做这样的事情?

PS:我需要同时使用 appPtr & app类型。

最佳答案

可以使用struct前向声明来完成。这是实现该概念的示例代码:

#include <stdio.h>

struct app;
typedef struct app* appPtr;

struct app
{
char *data;
appPtr ptr;
};

int main(void)
{
struct app myApp = { "myApp", NULL };

printf("%s, %p\n", myApp.data, (void *) myApp.ptr);
return 0;
}

但是,正如问题评论中提到的,我不建议将其作为正确的做法,因为它会混淆代码,并且更多间接级别会使事情变得困惑。

关于c - 在其字段中声明指向结构的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35902440/

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