Help with singly link list....
I have researched all over the internet yet I cannot figure out why this code doesn't work. Any suggestions and instructions on how to fix the problems will be greatly appreciated.
Code:
#define _GNU_SOURCE 1
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <getopt.h>
#include <sys/types.h>
#include <sys/wait.h>
typedef enum
{
FALSE = 0,
TRUE = 1
} Bool;
struct node
{
char *x;
struct node *next;
};
struct node *tptr = NULL, *cptr = NULL;
void addNode(char *input);
int main()
{
ssize_t readReturn = 0;
size_t bufLen = 0;
char *input;
int x = 0;
Bool stillGoing = TRUE;
while(stillGoing)
{
printf("enter text: ");
readReturn = getline(&input, &bufLen, stdin);
for(x = 0; x < strlen(input) + 1; ++x)
{
if(input[x] == '\n')
{
input[x] = '\0';
}
}
if((strncmp(input,"exit",4)) == 0)
{
stillGoing = FALSE;
break;
}
addNode(input);
}
if(tptr!=NULL)
{
for(cptr = tptr; cptr != NULL; cptr = cptr->next)
printf("%s\n", cptr->x);
}
/*for some reason tptr is ALWAYS null at this point*/
else
printf("something isn't right\n");
/*i know these frees arent complete i have yet to code this part*/
free(cptr);
free(tptr);
free(input);
return 0;
}
void addNode(char *input)
{
struct node *nptr;
cptr = tptr;
if ((nptr = malloc(sizeof(struct node))) != NULL)
{
nptr->x = input;
nptr->next = NULL;
if(tptr == NULL)
{
tptr = nptr;
}
else
{
while(cptr->next != NULL)
{
cptr = cptr->next;
}
cptr->next = malloc(sizeof(struct node));
cptr->next = nptr;
}
}
else
{
fprintf(stderr, "%s", "Not enough memory.\n");
exit(EXIT_FAILURE);
}
}
thanks for your help.
**edit
i fixed the tptr always being null problem. I accidently made tptr and cptr local variables. But im getting the output:
exit
exit
when it tries to list the contents of the list.