Tensora
Tensora

Reputation: 53

Is this a linked list?

I just did this code and its so difficult to check if the list is linked as it should. Is it possible to see if I have linked the list correctly?

.h file:

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

struct talstrul
{
    int num;
    struct talstrul *next;


};

.c file:

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

void main()
{   typedef struct talstrul talstrul;
    int vek[5] = {1,2,3,4,5};
    talstrul *pek1=NULL;
    int langd = sizeof(vek)/sizeof(vek[0]);

    int i;
    for(i=0; i<langd; i++)
    {
        talstrul obj1;
        obj1.num = vek[i];
        obj1.next = pek1;
        pek1 = &obj1;

    }

    printf("%d",*pek1);
}

I know atleast that pek1 Points to the value 5 so something is correct atleast :)

What if I change the main program to:

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

void main()
{   typedef struct talstrul talstrul;
    int vek[] = {1,2,3,4,5,9};
    talstrul *pek1=NULL;
    int langd = sizeof(vek)/sizeof(vek[0]);

    int i;
    for(i=0; i<langd; i++)
    {
        talstrul *obj1 = malloc(sizeof(talstrul));
        obj1->num = vek[i];
        obj1->next = pek1;
        pek1 = obj1;

    }

    printf("%d",*pek1);
}

Should the list be saved now?

Upvotes: 0

Views: 127

Answers (1)

Sean Duggan
Sean Duggan

Reputation: 1133

As I understand how structs get allocated and deallocated, your "talstrul" items are being built on the stack and then destroyed at the end of it. You need to allocate them using malloc (and, of course, free it up using free at the end) and then assign the resulting pointer to your "next" value.

Also, you need to keep track of where your "head" object is. Every object points forward, not backwards, which means that at the end, you have a pointer to the last object, but no way of finding where the first object is.

Upvotes: 1

Related Questions