这是简单的C源文件:
struct data{
int a;
char * b;
double c;
};
struct data mydata;
struct data *ptr;
ptr = &mydata;
ptr->a = 1;
ptr->b = NULL;
ptr->c = 0.1;
当我运行命令时:
clang -fsyntax-only source.c
我有这个输出:
source.c:11:1: warning: type specifier missing, defaults to 'int' [-Wimplicit-int]
ptr = &mydata;
^
source.c:11:1: error: redefinition of 'ptr' with a different type: 'int' vs 'struct data *'
source.c:9:14: note: previous definition is here
struct data *ptr;
^
source.c:13:1: error: unknown type name 'ptr'
ptr->a = 1;
^
source.c:13:4: error: expected identifier or '('
ptr->a = 1;
^
source.c:14:1: error: unknown type name 'ptr'
ptr->b = NULL;
^
source.c:14:4: error: expected identifier or '('
ptr->b = NULL;
^
source.c:15:1: error: unknown type name 'ptr'
ptr->c = 0.1;
^
source.c:15:4: error: expected identifier or '('
ptr->c = 0.1;
^
1 warning and 7 errors generated.
答案 0 :(得分:3)
以下四行只有在功能中出现时才有效:
ptr = &mydata;
ptr->a = 1;
ptr->b = NULL;
ptr->c = 0.1;
(mydata
和ptr
被理解为全局变量。)
如果将它们包含在原型int main()
的函数中,那么一切都会好的。 (C编译器期望找到一个名为main
的函数,我给你的原型是C标准接受的原型。)
答案 1 :(得分:1)
C无法解析这样的语句。它不是Python: - )
您需要将语句括在函数中。例如:
struct data{
int a;
char * b;
double c;
};
struct data mydata;
int main() {
struct data *ptr;
ptr = &mydata;
ptr->a = 1;
ptr->b = NULL;
ptr->c = 0.1;
}