user2135885
user2135885

Reputation: 79

Linked list, why am I getting the Incompatible type and incomplete struct error

Let say I have 2 struct.

    typedef struct name{
    char*name;
    struct test *next;
    }name_t;

    typedef struct test {
    int grade;
    int studentNumber;
    struct test *next;
    }test_t;

so the marker have a pointer to the test how would I go create the link list?

I tried this

name_t *marker1 = malloc(sizeof(name_t));
// added name from another function
test_t *temp= malloc(sizeof(test_t));
// add the grade and student number from another function
if(marker1->next==NULL)
marker1->next=temp;

but it gives me the error

how would I go about fixing this? This is my first time coding linked list so any help would be appreciated

edit: also I made the following into a function

void test(name_t* marker1,int data)
{
        test_t *temp= malloc(sizeof(test_t));
        test_t *location=NULL;
        temp->grade=data;
        temp->next=NULL;
        location=marker1->next;
        if(location==NULL)
        {
        //  printf("%i \n",temp->grade);
            marker1->next=temp;
        }
        else
        {
            while(location!=NULL)
            {
                printf("%i \n",location->grade);
                printf("%p \n",location->next);
                location=location->next;
            }
            location=temp;
        }
}

it does not seem to go though the list for some reason. Why?

Upvotes: 0

Views: 81

Answers (2)

Kranthi Kumar
Kranthi Kumar

Reputation: 1264

There is an error in the second block of your program. You have written

if(marker1==NULL)
marker1->next=temp;

Previous to this you have written

name *marker1 = malloc(sizeof(name));

marker1 will be NULL only when malloc is not able to allocate any memory for you and returns NULL. When marker1 is NULL, you cannot access marker1->next which leads to a segmentation fault. Malloc returns NULL when you ask for the amount of memory which crosses the limits and the if statement you have written will not be true. But the statement inside the if block should be avoided. It is a wrong practice to code where you are trying to access the data when the pointer is NULL.

Upvotes: 0

Alexey Frunze
Alexey Frunze

Reputation: 62048

struct test *next; refers to a tag name test.

typedef struct THIS_IS_WHERE_TAG_NAME_SHOULD_BE {
  ...
} test;

And you don't have such a tag name anywhere. Add it.

Upvotes: 2

Related Questions