Ognjen Stefanovic
Ognjen Stefanovic

Reputation: 404

Array of structure type. with pointer inside of structure

I'm missing something, probably very stupid, but I have no ideas anymore, I need some help.

#include <stdio.h>
#include <stdlib.h>

typedef struct person{
    char name[10];
    int *age;
} PERSON;

int main(){
    int i, n;
    scanf("%d", &n);
    PERSON *arr = (PERSON*)calloc(n, sizeof(PERSON));
    for(i = 0; i < n; i++){
        gets(arr[i].name);
        // scanf("%d", arr[i].age);
    }
        for(i = 0; i < n; i++){
        printf("%s", arr[i].name);
//          printf("%d", arr[i]->age));
    }


    return 0;
}

So, I cannot enter or read the age of any structure. I need a dynamic array of persons and in each person, I need a new dynamic array as well (this is a simplified version of the original code, but the error is same).

I have commented my last tries so you can see how I tried to do it.

Error I get is [Error] invalid type argument of '->' (have 'PERSON').

Upvotes: 0

Views: 63

Answers (1)

user2736738
user2736738

Reputation: 30926

Because age is a pointer not pointing to any memory. You have to either allocate memory and make that int* point to it OR change the structure definition to contain an int. Otherwise you were simply passing an indeterminate pointer value to scanf - this is undefined behavior. You can do this

arr[i].age = malloc(sizeof *arr[i].age);
if(!arr[i].age){
    perror("malloc");
    exit(EXIT_FAILURE);
}

and then use it in scanf. scanf("%d",arr[i].age); Print it

printf("%d\n",*arr[i].age);

The more natural solution would be to

typedef struct person{
    char name[10];
    int age;
} PERSON;

And use it accordingly. Then it would be something like

scanf("%d",&arr[i].age);

and

printf("%d\n",arr[i].age);

To clarify the error a bit:

arr[i]->age
\----/

This is a PERSON structure instance over which you apply the ->, which is why the error.

Check the return value of malloc,scanf etc. It would help you detect the error cases that may occur. gets is deprecated. Use fgets instead.

Upvotes: 4

Related Questions