0

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').

1
  • 1
    Do not use the function gets; It has been removed from the standard, and for good reason. Commented Feb 8, 2018 at 18:39

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@coderredoc was just trying to amplify, not correcting

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.