Chris Philp Chris Philp - 1 month ago 11
C Question

Trying to access elements of linked-list structures in C and calling functions on struct elements

I am starting out on C and i was just wondering how I would declare these linked lists structures in the main function so that I could call the functions on them, and then how I would print the values from the elements of the linked list.

Thanks for the help

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

void main() {

}

struct element {
struct element * next;
int data;
};
struct linked_list {
struct element * head;
};

void append_int(struct linked_list * list, int val) {
struct element * elem = malloc(sizeof(struct element));
elem->data = val;
elem->next = NULL; // Really important to explicitly set this to null. Malloc does not zero memory
if (list->head == NULL) {
// Empty list, we need to append to head
list->head = elem;
} else {
// List has some elements, find the end and append to that
struct element * tail = list->head;
while (tail->next != NULL) {
tail = tail->next;
}
tail->next = elem;
}
}

void deletehead(struct linked_list * list) {
while(list->head) {
struct element * temp_head = list->head->next;
free(list->head);
list->head = temp_head;
}
}

void inserthead(struct linked_list * list, int val) {
struct element * new_node = malloc(sizeof(struct element));
new_node->data = val;
struct element * temp_head2 = list->head;
list->head = new_node;
new_node->next = temp_head2;
}

Answer

you can create the struct linked_list, that will hold the pointer to the first "link", the first element that is your "object" like in Object Oriented programming.

also don't forget to forward declare your functions if needed!

to create a linked list:

struct linked_list* list = malloc(sizeof(linked_list));

to call functions on it:

inserthead(list, 5);

if you are coming from an oop background, all functions are static, you can think of passing the pointer to the function as calling it like "list.insert()".

Comments