I have been working on a program in C99 which is based heavily around structs. I found that I could create linked lists of structs, and thought to give it a try.
The following is a miserable attempt, reworked about 50 times, that is meant to do the following:
1) Create a struct of type BASE in the main method, which contains the head of a linked list (CHAIN).
2) Pass this BASE struct to another function, which will append additional CHAIN elements to the end of the linked list.
3) Print the linked lists elements in main, as proof to myself that the changes are not just in the other method.
#include <stdlib.h>
#include <stdio.h>
typedef struct Base {
//many things
struct Chain *head;
} BASE;
typedef struct Chain {
int x;
struct Chain *next;
} CHAIN;
void extendChain(BASE *Data, int length);
int main() {
BASE Data;
CHAIN *pointer;
Data.head = 0;
int length = 10; //userInput(); // gets integer
extendChain(&Data, length);
pointer = Data.head;
while (pointer) {
printf("%d\n", pointer->x);
pointer = pointer->next;
}
}
void extendChain(BASE *Data, int length) {
CHAIN *position;
position = Data->head;
for (int i=0; i<length; ++i) {
if (!Data->head) {
// this will set the first value, the first time this is run.
Data->head = malloc(sizeof(CHAIN));
Data->head->x = -1; // set values here. Irrelevant.
position = Data->head;
} else if (position) {
while (position->next) {
position = position->next;
}
position = malloc(sizeof(CHAIN));
position->next = 0;
position->x = i; // placeholder
}
}
}
This has turned out terribly, and I realize that my example doesn't begin to work even in theory (but I gave it my best shot). I'm beginning to think that the only way to do this is if I do it all in the same method, which I successfully managed to do earlier, however this will quickly become messy, and a method would definitely be best.
Does anyone have a creative way of adding X elements to a linked list when passed only a struct containing the header of this linked list? Much appreciated, as always.