0
votes

I can't understand why i get this error : The error is : "incompatible types when assigning to type 'PERSOANA * {aka struct *}' from type 'PERSOANA {aka struct }' " Can you please explain me where is the mistake ?

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

typedef struct {
    char name[20];
    char name2[20];
    char cnp[15]; 

} PERSON;

PERSON read_array(int n);

int main()
{
    int n;
    printf("n = ");
    scanf("%d", &n);
    PERSON *v;
    v = read_array(n); //here i get the error

    return 0;
}

PERSON read_array(int n) {
    PERSON *v;
    v = malloc(n * sizeof(PERSON));
    for(int i = 0; i < n; i++) {
        printf("name=");
        gets(v[i].name);
        //more instr
    }
    return v; // and also here
}
2
You try to return a pointer to a struct when you declared to return a struct. - Osiris
PERSON *read_array(int n) should be the correct syntax. - Osiris
Please quote the error message in full and verbatim. It is unlikely that what you quoted is actually the exact and full message. - Yunnosch
Now it works, thx a lot mate !:) - ballow
type of v is PERSON* and return type of the function prototype is PERSON. - Stef1611

2 Answers

3
votes

Return a pointer to PERSON, not the object PERSON.

// PERSON read_array(int n);
PERSON *read_array(int n);
//     ^

// PERSON read_array(int n) {
//     v
PERSON *read_array(int n) {
1
votes

I can't understand why i get this error : Incompatible types when assigning to type PERSON from type PERSON.

I am reasonably confident that you do not get that error, but if you actually do then you should switch to a better compiler. I speculate that the error you get is instead

Incompatible types when assigning to type PERSON * from type PERSON

, because that's in fact what you are trying to do, given your declaration of function read_array().

From implementation and use, it appears that you want that function to return a pointer to a structure rather than a copy of the structure. That would be

PERSON *read_array(int n);

... and the same in the function definition.