0

The program below uses a pointer to an array of struct Student. It declares the pointer to the array of struct, prompts the user for the data to input and displays the data input. I get this compilation error: request for member ‘Age’ in not a structure or union. If I understand correctly, Age is of integer type, hence the prefix & so as to store data in it; and the prefix * because the program uses a pointer to the array of struct. How do I input data into 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]);
    }
}
1
  • 1
    I don't see the need to pass a pointer to Student to the displayStudent function, and I don't see a need for the double-pointer passing to the inputStudent function. Or having the array of pointers and dynsamic allocation in main. Commented Nov 21, 2015 at 6:29

2 Answers 2

1

In your function void inputStudent(struct Student **s)-

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

The & operator should be outside. You need to write like this -

 scanf("%d", &((*s)->Age));
Sign up to request clarification or add additional context in comments.

Comments

0

The program should work with following changes: 1. Change the call to inputStudent and pass the parameter without '&', that is, inputStudent(s[i]); 2. In function inputStudent(), change the scanfs: scanf("%s", s->Name); scanf("%d", &(s->Age));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.