关于 标准C的标记化结构初始化语法 的一个疑问
已知一个结构,定义如下
struct book {
char title[MAXTITL];
char author[MAXAUTL];
float value;
};
C99支持结构的指定初始化项目,其语法与数组的指定初始化项目近似。只是,结构的指定初始化项目使用点运算符和成员名(而不是方括号和索引值)来标识具体的元素。例如,只初始化book结构的成员value,可以这样做:
struct book surprise = {
.value = 10.99
};
可以按照任意的顺序使用指定初始化项目:
struct book gift = {
.value = 25.99,
.author = "James Broadfool",
.title = "Rue for the Toad"
};
上述都是可以的,但是我想问 如果定义了个 struct book *gift 应该如何处理,因为*gift是需要malloc空间的,如果改成
struct book *gift = (XX *)malloc(sizeof(XX));
然后再
gift = {
.value = 25.99,
.author = "James Broadfool",
.title = "Rue for the Toad"
};
则编译器会报错: 错误:expected expression before ‘{’ token
所以想问下如果gift是指针 那如何处理。
我在看的一本linux驱动程序关于file_operations结构体定义scull_fops指针时候 是直接
struct file_operations scull_fops = {
******,
******,
}; 这样子的 那为什么不是*scull_fops 没malloc不会死么?
[解决办法]
用C99复合字面值(compound literals)
#define MAXTITL 64
#define MAXAUTL 64
struct book {
char title[MAXTITL];
char author[MAXAUTL];
float value;
};
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
struct book *gift;
gift = (struct book *)malloc(sizeof(struct book));
*gift = (struct book) {
.value = 25.99,
.author = "James Broadfool",
.title = "Rue for the Toad"
};
return 0;
}