【问题标题】:How to input data in a pointer to an integer?如何在指向整数的指针中输入数据?
【发布时间】: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


【解决方案1】:

在你的函数void inputStudent(struct Student **s)-

 scanf("%d", (*&s)->Age);   // *&s will evaluate to s 

&amp; 运算符应该在外面。你需要这样写-

 scanf("%d", &((*s)->Age));

【讨论】:

    【解决方案2】:

    该程序应适用于以下更改: 1.将调用改为inputStudent,传入不带'&'的参数,即inputStudent(s[i]); 2. 在函数 inputStudent() 中,更改 scanfs: scanf("%s", s->Name); scanf("%d", &(s->年龄));

    【讨论】:

      猜你喜欢
      • 2019-10-27
      • 2012-01-23
      • 2012-01-24
      • 1970-01-01
      • 2017-02-12
      • 2017-01-14
      • 1970-01-01
      • 2016-03-19
      • 1970-01-01
      相关资源
      最近更新 更多