Push on linked lists - C

Hello I'm dooing a program in c with linked lists and I don't know what i`m doing wrong. The problem is on the line: "podio novo = (struct podio) malloc(sizeof(podio));" inside of push. here is my code:

struct Sucesso {
    char nome_equipe[N1];
    float distancia_alvo;
    float tempo_propulsao;
};

struct Node {
    struct Sucesso *dados;
    struct Node *prox;
};

typedef struct Node podio;

void push(podio *p, struct Sucesso elem) {
    podio *novo = (struct podio*) malloc(sizeof(podio));
    if(novo != NULL) {
        novo->dados=elem;
        novo->prox=*p;
        *p=novo;
    } 
}

Upvotes: 0

Views: 95

Answers (2)

Jonathan Leffler
Jonathan Leffler

Reputation: 754090

The problem is that struct podio is an incomplete type unrelated to the type podio (aka struct Node) defined via typedef struct Node podio;. Therefore, the two types (podio * and struct podio *) are incompatible; they point to different types of object.

If you lose the struct in the malloc() line, your code should compile.

podio *novo = (podio *) malloc(sizeof(podio));

or:

podio *novo = malloc(sizeof(*novo));

There'll be those who castigate you for casting the result of malloc(); fortunately for you, I'm not one of them.

Upvotes: 2

Rohan
Rohan

Reputation: 53336

Problem is with these lines

novo->dados=elem;
novo->prox=*p;

Here novo->dados is struct Sucesso* but elem is struct Sucesso ie not a pointer. So you are assigning structure to a structure pointer which is not valid. You need to pass address of in elem in push().

And nove->prox is struct Node * but *p is podio *p aka struct Node *, so *p is padio not a pointer. So again you are assigning structure to pointer to structure.

Upvotes: 0

Related Questions