我有以下代码,它直接来自Head First C第5章,我使用Clang 7和GCC 6得到一个错误:
#include <stdio.h>
typedef struct {
const char* description;
float value;
} swag;
typedef struct {
swag* swag;
const char* sequence;
} combination;
typedef struct {
combination numbers;
const char* make;
} safe;
swag gold = {
"GOLD!",
1000000.0
};
combination numbers = {
&gold,
"6502"
};
safe s = {
numbers,
"RAMACON250"
};
int main()
{
printf("Contents = %s\n", s.numbers.swag->description);
}下面是错误:
> clang-7 -pthread -lm -o main main.c
main.c:29:5: error: initializer element is not a compile-time
constant
numbers,
^~~~~~~
1 error generated.我发现了许多类似的堆栈溢出问题,但似乎没有一个是完全相同的代码场景。下面是代码的REPL:
发布于 2019-07-24 12:54:40
初始化结构的方式是不正确的。该语法用于初始化C中的数组。以下是经过适当结构初始化的修改后的代码版本。
#include <stdio.h>
typedef struct {
const char* description;
float value;
} swag;
typedef struct {
swag* swag;
const char* sequence;
} combination;
typedef struct {
combination numbers;
const char* make;
} safe;
swag gold;
combination numbers;
safe s;
int main()
{
gold.description = "GOLD!";
gold.value = 10000.0;
numbers.swag = &gold;
numbers.sequence = "6502";
s.numbers = numbers;
s.make = "RAMACON250";
printf("Contents = %s\n", s.numbers.swag->description);
}这是有效的,但这不是一个很好的赋值指针变量的方法。对于char *,您需要使用strcpy;对于一般结构指针,您需要使用malloc。
https://stackoverflow.com/questions/57171440
复制相似问题