struct intitialization notation不能与堆分配存储一起使用 [英] struct intitialization notation not working with heap allocated storage
本文介绍了struct intitialization notation不能与堆分配存储一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用gcc(GCC)4.4.6,我试着编译这个程序 -
With gcc (GCC) 4.4.6 , I try to compile this program -
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 = {
.i = 10,
.ch = 'c',
};
这个用法称为指定初始值设定项,顾名思义,它只是用于初始化结构或数组,但您正在尝试的是赋值。
This usage is called designated initializer, as the name implies, it's only used to initialize struct or arrays, but what you are trying to do is assigning.
正确使用指定初始值:
The correct usage of designated initializer:
strcut B foo = {.i = 10, .ch = 'c'};
要分配结构,您仍然需要使用:
To assign the struct, you still need to use:
ptr->i = 10;
ptr->ch = 'c';
编辑:或者您可以像@Andrey T's答案:
EDIT: Or you can use a compound literal like in @Andrey T's answer:
*ptr = (struct B) {
.i = 10,
.ch = 'c',
};
这篇关于struct intitialization notation不能与堆分配存储一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文