Saiyan
Saiyan

Reputation: 197

How to input data in a pointer to an integer?

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]);
    }
}

Upvotes: 0

Views: 394

Answers (2)

Arun Kaushal
Arun Kaushal

Reputation: 631

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));

Upvotes: 0

ameyCU
ameyCU

Reputation: 16607

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));

Upvotes: 1

Related Questions