【发布时间】:2015-11-21 06:22:55
【问题描述】:
下面的程序使用一个指向 struct Student 数组的指针。它声明指向结构数组的指针,提示用户输入数据并显示数据输入。我收到此编译错误:request for member ‘Age’ in not a structure or union。如果我理解正确,Age 是整数类型,因此前缀 & 以便在其中存储数据;和前缀 * 因为程序使用指向结构数组的指针。如何在 Age 中输入数据?
#include <stdio.h>
#include <stdlib.h>
struct Student{
char Name[30];
int Age;
};
void inputStudent(struct Student **s){
static int i;
i = i + 1;
printf("\nEnter data for student %d\n", i);
printf("\tName: ");
scanf("%s", (*s)->Name);
printf("\tAge: ");
scanf("%d", (*&s)->Age);
}
void displayStudent(struct Student *s){
static int i;
i = i + 1;
printf("\nDisplaying data for student %d\n", i);
printf("\tName: %s\n", (*s).Name);
printf("\tAge: %d\n", (*s).Age);
}
int main(){
struct Student *s[20]; //declare array of pointer to struct
int n, i = 0, position = 0;
printf("Enter number of students (below 20): ");
scanf("%d", &n);
getchar();
for (i = 0; i < n; i++){
s[i] = (struct Student*) malloc (sizeof(struct Student)); //allocate memory for each element in array
inputStudent(&s[i]);
}
for (i = 0; i < n; i++){
displayStudent(s[i]);
}
}
【问题讨论】:
-
我认为不需要将指向
Student的指针传递给displayStudent函数,我认为不需要将双指针传递给inputStudent函数.或者在main中有指针数组和动态分配。
标签: c arrays pointers struct integer