Tensora
Tensora

Reputation: 53

Error in simple linked list code

I try to create a simple linked list out of a integer vector. Why is this not working? The errors I get are:

'=' : incompatible types - from 'talstrul *' to 'node *'
'=' : cannot convert from 'talstrul*' to talstrul'

This is the .h file:

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

typedef struct
{
    int num;
    struct node *next;


} talstrul;

This is the .c file:

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

int main()
{   int vek[5] = {1,2,3,4,5};

    int langd = sizeof(vek)/sizeof(vek[0]);

    printf("%d",langd);

    talstrul *temp = malloc(sizeof(talstrul));
    talstrul *pek1 = NULL;
    int i;
    for(i=0; i<langd; i++)
    {

    pek1 -> num = vek[i];
    pek1 -> next = *temp;   
    *temp = pek1;
    }
}

Upvotes: 1

Views: 77

Answers (3)

BLUEPIXY
BLUEPIXY

Reputation: 40145

typedef struct node {
    int num;
    struct node *next;
} talstrul;
...
int vek[5] = {1,2,3,4,5};

int langd = sizeof(vek)/sizeof(vek[0]);

talstrul *pek1 = NULL;
int i;
for(i=0; i<langd; i++){
    talstrul *temp = malloc(sizeof(talstrul));

    temp -> num = vek[i];
    temp -> next = pek1;   
    pek1 = temp;
}

Upvotes: 0

Soumen
Soumen

Reputation: 1078

Another problem with the code :

pek1 is assigned to NULL. Yet you try to assign pek1->num and pek1->next. You should do memory allocation for pek1 first.

Upvotes: 0

Eric J.
Eric J.

Reputation: 150108

temp is of type talstrul *

talstrul *temp = malloc(sizeof(talstrul));

You are trying to assign to next, which is of type node *

struct node *next;

Further

pek1 -> next = *temp;

dereferences temp, yielding a talstrul. You should not dereference the pointer.

The compiler is giving you a pretty good explanation of what is going wrong.

Upvotes: 4

Related Questions