我试图通过函数中的复合文字来初始化 struct .在解决了我的问题的一部分(参见Use of compound literal inside a function to init a variable in C)之后,我遇到了一个新问题,其中一个成员(ptr_mb)必须是指向变量的指针.

这是我们的密码:

typedef struct {
  int i_mb;
  int * ptr_mb;
} my_struct_t;

void init_struct(my_struct_t **my_struct, int * const ptr) {
  *my_struct=&(static my_struct_t) {.i_mb=3, .ptr_mb= ptr};
}

int main() {
  int a;
  my_struct_t *my_struct;
  
  // my_struct = &(my_struct_t) {.i_mb=3, .ptr_mb=&a}; It is OK

  // Try to initialize it in a function
  init_struct(&my_struct, &a);
  
}

main(),它工作(cf注释行在程序中)

发出编译错误.在函数init_structptr is not a constant(行:*my_struct=&(static my_struct_t) {.i_mb=3, .ptr_mb= ptr};)中.

a是在main()中声明的变量.因此,它的地址是不变的.我试着用(int const *)(int * const)(int const * const),...有时这是废话,但只是try 和没有工作.

有没有可能在函数中进行这样的初始化,就像在main()中的工作方式一样?

(Rq. static使用我知道这是一个C23标准,而且该标准尚未发布;详细信息,请参见以下答案:Use of compound literal inside a function to init a variable in C.

推荐答案

在初始化过程中不要这样做.添加一个任务.

typedef struct {
  int i_mb;
  int * ptr_mb;
} my_struct_t;

void init_struct(my_struct_t **my_struct, int * const ptr) {
  *my_struct = &(static my_struct_t){.i_mb=3};
  (*my_struct) -> ptr_mb = ptr;
}

int a = 10;
int main() {

  my_struct_t *my_struct;
  
  // Try to initialize it in a function
  init_struct(&my_struct, &a);  

  /* ... */ 
}

C++相关问答推荐

理解没有返回语句的递归C函数的行为

如何在IF语句中正确使用0.0

在C中将通用字符名称转换为UTF-8

#If指令中未定义宏?

C语言编译阶段与翻译阶段的关系

fwrite无法写入满(非常大)缓冲区

为什么该函数不将参数值保存到数据 struct 中?

Char变量如何在不使用方括号或花括号的情况下存储字符串,以及它如何迭代到下一个字符?

使用sscanf获取零个或多个长度的字符串

是否需要包括<;errno.h>;才能使用perror?

我的C函数起作用了,但我不确定为什么

如何在双向表中实现线程安全,每个条目仅使用4位,同时避免任何全局锁?

为四维数组中的Dim-1和Dim-3重新分配空间

为什么编译器不能简单地将数据从EDI转移到EAX?

Valgrind用net_pton()抱怨

使用mmap为N整数分配内存

哪些C++功能可以在外部C块中使用

C 错误:对 int 数组使用 typedef 时出现不兼容的指针类型问题

如何向 execl 创建的后台程序提供输入?

strlen 可以是[[未排序]]吗?