main 中未声明结构字段
大家好,我正在编写一个 C 程序,我想要一个分配了内存并用文件中的数据填充的结构数组。这是我的结构的 typedef:
typedef struct {
char name[5];
int age;
} person;
然后在我的 main 函数中我这样做:
person *A ;
int i ;
FILE * fin;
fin = fopen( "people", "r" );
A = ( person * ) malloc( sizeof(person) * 10 );
if ( A == NULL ) { printf( "Error mallocing \n" ) ; return -1 ; }
for( i = 0; i < 10; i++ ) {
fscanf( fin, "%s %d", name->A[i], age->A[i] );
}
现在不幸的是,当我尝试编译时,我收到错误,名称和年龄在 main 中未声明。我以前从未尝试过使用 fscanf 来创建结构,但我在这里有点不知所措。预先感谢任何知道任何事情的人!
Hey all, I'm writing a C program, and I want to have an array of structs malloc'd up and filled with data from a file. Here's my typedef for the struct:
typedef struct {
char name[5];
int age;
} person;
And then in my main function I do this:
person *A ;
int i ;
FILE * fin;
fin = fopen( "people", "r" );
A = ( person * ) malloc( sizeof(person) * 10 );
if ( A == NULL ) { printf( "Error mallocing \n" ) ; return -1 ; }
for( i = 0; i < 10; i++ ) {
fscanf( fin, "%s %d", name->A[i], age->A[i] );
}
Now unfortunately when I try to compile I get the error that name and age are undeclared in main. I've never tried using fscanf to make structs before, but I'm at a bit of a loss here. Thanks in advance to anyone who knows anything!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您只是不小心使语法倒退了(事实上,索引指针返回一个实际的结构,而不是指向它的指针,因此不需要指向成员运算符
->
的指针):A[i].name
和&(A[i].age)
。同时检查fopen
的返回值可能是一个好主意。You just accidentally got your syntax backwards (that and the fact that indexing the pointer returns an actual struct, not a pointer to it so the pointer to member operator
->
is not needed):A[i].name
and&(A[i].age)
. Also checking the return value fromfopen
might be a good idea.