I'm trying to write a program that uses linked-lists, the intent is to improve my understanding of pointers.
I ran into a strange problem (sigh as usual) ....everytime i call my appendlist() function an element is added to the linked-list but if the function is called on the same line it overrides the previous element....can somebody please explain to me how this is happening???
The Problem:
Code:
void appendlist(struct ll *curlist, void *datax){
struct ll newlinkedlist = newlist(datax); //local allocation problem??? something to do with stack/heap?!!
struct ll *end = endlist(curlist);
end->flink = &newlinkedlist;
newlinkedlist.blink = end;
newlinkedlist.flink = NULL;
}
The Method I call the Function:
Code:
int main(){
struct ll alist = newlist("BEGIN"); //new element1 added
int i,ii;
for(i=0;i<100;i++){
char *text = (char*)malloc(11);
for(ii=0;ii<10;ii++){
text[ii] = rand() % 108+126;
}
text[ii] = 0;
appendlist(&alist,text); //overrides element2
appendlist(&alist,text); //overrides element3
}
appendlist(&alist,"goat"); //new element4 added
appendlist(&alist,"pig"); //new
appendlist(&alist,"fry"); //new
appendlist(&alist,"shy"); //new
appendlist(&alist,"ape"); //...
printlist(&alist);
return 0;
}
The Semi-Working Code:
Code:
#include <string.h>
#include<stdlib.h>
#include<stdio.h>
struct ll {
struct ll *blink;
void *data;
struct ll *flink;
};
struct ll newlist(void *datax){
struct ll newlinkedlist;
newlinkedlist.blink = NULL;
newlinkedlist.data = datax;
newlinkedlist.flink = NULL;
return newlinkedlist;
}
struct ll *beglist(struct ll *list){
struct ll temp = *list;
while(temp.blink != NULL){
temp = *temp.blink;
}
if(temp.flink != NULL){
temp = *temp.flink;
return temp.blink;
}
else{
return list;
}
}
struct ll *endlist(struct ll *list){
struct ll temp = *list;
while(temp.flink != NULL){
temp = *temp.flink;
}
if(temp.blink != NULL){
temp = *temp.blink;
return temp.flink;
}
else{
return list;
}
}
void printlist(struct ll *list){
struct ll *ptrfinder = beglist(list);
int i = 0;
while(ptrfinder != NULL){
printf("%i:%s\n",i++,ptrfinder->data);
ptrfinder = (ptrfinder->flink);
}
}
void appendlist(struct ll *curlist, void *datax){
struct ll newlinkedlist = newlist(datax); //local allocation problem??? something to do with stack/heap?!!
struct ll *end = endlist(curlist);
end->flink = &newlinkedlist;
newlinkedlist.blink = end;
newlinkedlist.flink = NULL;
}
int main(){
struct ll alist = newlist("BEGIN"); //new element1 added
int i,ii;
for(i=0;i<100;i++){
char *text = (char*)malloc(11);
for(ii=0;ii<10;ii++){
text[ii] = rand() % 108+126;
}
text[ii] = 0;
appendlist(&alist,text); //overrides element2
appendlist(&alist,text); //overrides element3
}
appendlist(&alist,"goat"); //new element4 added
appendlist(&alist,"pig"); //new
appendlist(&alist,"fry"); //new
appendlist(&alist,"shy"); //new
appendlist(&alist,"ape"); //...
printlist(&alist);
return 0;
}