正如标题所说,我有这样的代码:
typedef struct Book{
int id;
char title[256];
char summary[2048];
int numberOfAuthors;
struct Author *authors;
};
typedef struct Author{
char firstName[56];
char lastName[56];
};
typedef struct Books{
struct Book *arr;
int numberOfBooks;
};
我从gcc那里得到了这些错误:
bookstore.c:8:2: error: unknown type name ‘Author’
bookstore.c:9:1: warning: useless storage class specifier in empty declaration [enabled by default]
bookstore.c:15:1: warning: useless storage class specifier in empty declaration [enabled by default]
bookstore.c:21:2: error: unknown type name ‘Book’
bookstore.c:23:1: warning: useless storage class specifier in empty declaration [enabled by default]
如果我像这样更改typedefs,则不会出现任何警告和错误:
typedef struct{
char firstName[56];
char lastName[56];
} Author;
在搜索了和谷歌了几个小时之后,我想不出为什么第一个实现不能工作。
发布于 2013-07-18 18:09:42
typedef
的语法如下:
typedef old_type new_type
在第一次尝试中,您定义了struct Book
类型,而不是Book
。换句话说,您数据类型称为struct Book
,而不是Book
。
在第二种形式中,您使用了正确的typedef
语法,因此编译器可以识别名为Book
的类型。
发布于 2013-07-18 18:07:47
在定义Book之前,您只需要定义Author。
您在Book中使用Author,因此需要在此之前定义它。
发布于 2013-07-18 18:12:51
我想这会帮助你理解。http://www.tutorialspoint.com/cprogramming/c_typedef.htm
bookstore.c:8:2: error: unknown type name ‘Author’
bookstore.c:21:2: error: unknown type name ‘Book’
之所以生成它们,是因为您必须在使用它们之前定义它们。将结构"Author“& "Books”移到结构"Book“的上方。这将会解决这个问题。
此外,你得到的警告解释了为什么会有问题,编译器认为"typedef struct Author“是不必要的,因为你没有正确地定义结构,所以编译器没有什么有用的东西来”读取“。
既然您已经知道答案应该在下面的表单中
typedef struct {
...
...
...
} struct-name;
坚持下去。
https://stackoverflow.com/questions/17720223
复制相似问题