I've really been struggling with PSET5 so I decided to take a step back and write a simple linked list program. My program take in an array of characters as a command line argument and stores each character in a linked list and prints them out.
My program more works as is, but when I move one line of code the list won't print and I can't figure out why.
Near the bottom of my code I remove:
// DELETE THIS NEXT LINE
printList(list);
Near the start of the code I uncomment:
// UNCOMMENT THIS LINE
// printList(list);
Moving this one line of code cause the printing to not work and I can't figure out why. I've screwed around with the debugger for quite some time, and it seems like my printList() function doesn't think anything is in the list. Why is this?
Both my addToList() and printList() functions take the *list variable as a pointer? Doesn't that mean the list is passed by reference and it should still exist by the time printList() calls it?
#include <stdio.h>
#include <stdlib.h>
typedef struct character
{
struct character* next;
char storedCharacter;
}
character;
void addToList(character *list, char* argv[]);
void printList(character *list);
int main(int argc, char* argv[])
{
// start a list
character *list = NULL;
addToList(list, argv);
// UNCOMMENT THIS LINE
// printList(list);
}
void addToList(character *list, char* argv[])
{
for (int i = 0; i < 45; i++)
{
if (argv[1][i] == '\0')
{
break;
}
else if (i == 0)
{
character *c = malloc(sizeof(character));
c->storedCharacter = argv[1][i];
c->next = NULL;
list = c;
}
else
{
character *c = malloc(sizeof(character));
c->storedCharacter = argv[1][i];
// point new node to start of list
c->next = list;
list = c;
}
}
// DELETE THIS NEXT LINE
printList(list);
}
void printList(character *list)
{
for (character *tmp2 = list; tmp2 != NULL; tmp2 = tmp2->next)
{
printf("%c\n", tmp2->storedCharacter);
}
}