使用 gcc (GCC) 4.4.6 ,我尝试编译这个程序 -
1 #include <stdio.h>
2 #include <stdlib.h>
3
4 int main(int argc, char *argv[])
5 {
6
7 struct B {
8 int i;
9 char ch;
10 };
11
12 struct B *ptr;
13
14 ptr = (struct B*) calloc(1, sizeof(struct B));
15
16 *ptr = {
17 .i = 10,
18 .ch = 'c',
19 };
20
21 printf("%d,%c\n", ptr->i, ptr->ch);
22
23 return 0;
24 }
25
$ make
gcc -g -Wall -o test test.c
test.c: In function ‘main’:
test.c:16: error: expected expression before ‘{’ token
make: *** [test] Error 1
最佳答案
您所说的“结构初始化符号”使用术语“初始化”是有原因的:它旨在用于初始化 上下文。您要做的根本不是初始化。这是任务。此语法不会立即在赋值上下文中起作用。
为了继续使用这种方便的语法,您必须创建另一个相同类型的结构,使用这种语法对其进行初始化,然后使用赋值将该结构复制到您的结构中。例如
ptr = calloc(1, sizeof *ptr);
const struct B INIT = {
.i = 10,
.ch = 'c',
};
*ptr = INIT;
这已经实现了你想要做的事情,但你可以通过使用 C 语言的复合文字特性使上面的内容更紧凑
ptr = calloc(1, sizeof *ptr);
*ptr = (struct B) {
.i = 10,
.ch = 'c',
};
基本上,后一个代码示例可能就是您要查找的内容。但是,请注意,从概念上讲,这仍然不是初始化。它是一个赋值,创建一个 struct B
类型的临时对象,然后将其分配给您的 *ptr
对象。
关于c - 结构初始化符号不适用于堆分配的存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18437050/