c - 错误 : request for member 'Name' in something not a structure or union

标签 c pointers struct member dynamic-arrays

我正在尝试编写一个程序,将文本文件 (data2.txt) 中的数据读取到动态数组中。然后将该数据打印到屏幕上。当我运行我的程序时,出现如下错误:

Error: request for member 'Name' in something not a structure or union.

我不明白为什么我会收到这个错误,因为我在我的程序中包含了一个包含结构的头文件。数组 P 的大小是文件中的第一个整数。任何帮助\指导将不胜感激。

这是文本文件 data2.txt 的内容:


5
Martin Smith     22 2.2
Austin Clinton   18 3.1
Johnson          19 2.9
Maggie Jones     23 2.3
Tyler W Brown    16 3.4 

这是头文件的内容:


typedef struct RECORD
{
char Name[15];
int Age;
float Gpa;

};

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "Mo.h"

int main()
{

int n;
int number = 0;
int i=0;


FILE * fpointer;
    fpointer = fopen("data2.txt", "r");

    fscanf(fpointer,"%d",&number);
    n = number;

    printf("Size value is: %d \n", n);

   int *P = malloc(n*sizeof(int));

[错误显示在下一行]

  fscanf(fpointer,"%s %d %f", P[i].Name , &P[i].Age, &P[i].Gpa);

   while(! feof(fpointer))
   {
    printf("%s %d %.1f\n",P[i].Name , P[i].Age, P[i].Gpa);
     fscanf(fpointer, "%s %d %f",P[i].Name , &P[i].Age, &P[i].Gpa);

     i++;
   }



free(P);


fclose(fpointer);

printf("\n\n");
system("PAUSE");
return 0;
}

最佳答案

int *P = malloc(n*sizeof(int));

这里的P是一个int类型的指针,你需要的是

struct RECORD *p = malloc(n * sizeof(struct RECORD));

p 应该是 struct RECORD

类型的指针

关于c - 错误 : request for member 'Name' in something not a structure or union,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32883115/

相关文章:

c++ - 如何在 C++ 中遍历 void* 的字节?

C - 这个变量的类型是什么?

python - 在 python 中使用 swig 包装的 typedef 结构和枚举来转换字符串/缓冲区数据

c - "Expected declaration before ' struct ' "声明函数时?

将结构复制到相同类型结构的数组中

c - 循环在第一次后跳过 scanf 语句

c - 将 fopen 与 temp 系统变量一起使用

c - 警告 : case not evaluated in enumerated type?

C:指向指针地址的指针,需要说明

c++ - 这是在 C++ 中使用指针的好方法吗?