im currently implementing a basic linked list structure on C.
Basically im parsing a txt file, and I buffer each line into a Node which contains a pointer to an array of integers. The problem is, that my data (the array of integers) doesn't save correctly / i don't know how to iterate through it correctly.
These are the structures that I use:
typedef struct Node { struct Node* next; struct Node* prev; int* data; int len; } Node; typedef struct LinkedList { Node* head; Node* tail; } LinkedList; and I use this method to create a new node from a buffered string:
int nodeManager(FILE* filePointer, char* buffer, char* token, LinkedList* linkedList) { token = strtok(buffer, DELIMITER); int* data = (int*)malloc(sizeof(int)); int dataIndex = 0; if (data == NULL) { fprintf(stderr, DATA_ALLOCATION_ERROR); freeLinkedList(linkedList); fclose(filePointer); return EXIT_FAILURE; } const char* insertPosition = token; while ((token = strtok(NULL, DELIMITER))) { data = realloc(data, dataIndex + 1); if (data == NULL) { fprintf(stderr, DATA_ALLOCATION_ERROR); freeLinkedList(linkedList); fclose(filePointer); return EXIT_FAILURE; } char *res; int num = (int) strtol(token, &res, 10); data[dataIndex] = num; dataIndex++; } Node* newNode = (Node*)malloc(sizeof(Node)); if (newNode == NULL) { freeLinkedList(linkedList); free(data); fclose(filePointer); return EXIT_FAILURE; } newNode -> prev = NULL; newNode -> next = NULL; newNode -> len = dataIndex; newNode -> data = data; if(strcmp(insertPosition, INSERT_TO_START) == 0) { addToStartLinkedList(linkedList, newNode); } else { addToEndLinkedList(linkedList, newNode); } return EXIT_SUCCESS; // TODO - Change } A line of input looks like this:
start,1,2,3,4,5,6,7,10,22,44,55,66,66,77 for some reason, node -> data doesn't get all the values that I assign in this method and I can't really tell why.
I tried to print the values like this:
for (int i = 0; i < newNode -> len; i++) { printf("%d,", (newNode -> data)[i]); } However, as I said, something quite doesn't work with my assigment, or I just don't know how to access the values correctly.
Would love to get some insight - thanks.