Hello, I am having this problem with a linked list. In a program I have created a method that links nodes together except when I check each node's data, all of them contain the same thing. This means that the lists is being created but not 100% correct. here is some of the code.
The data that is being looked is a created struct called String that is defined as :
here is the method that creates the linked list:Code:typedef struct {
char *str; /* str is a dynamic array of characters*/
int len; /* number of characters */
} String;
Code:void addNode(listNode** headRef, String data) {
listNode* newNode = (listNode *)malloc(sizeof(listNode));
newNode->data = data;
newNode->next = *headRef;
*headRef = newNode;
}
Here is the main method:
When I run the code it looks like this:Code:String data;// data recieved from user
listNode* list; // operation will be performed on this
listNode* printer;// used to traverse through list
int main(void) {
data.str = (char*)malloc(sizeof(char)); //allocate memory
printf("Enter a string:\n");
scanf("%s", data);
ListInitialize(list); //intitalize list
addNode(&list, data); // add a node to the list
printf("Enter another string:\n");
scanf(" %s", data.str);
addNode(&list,data);//add another node to the list
printf("%d\n",Length(list));// check the length of list
/** print each string in the list */
for(printer = list; printer != NULL; printer = printer->next) {
printf("%s\n", printer->data);
}
freeList(list);
return 0;
}
Quote:
Enter a string:
name1
Enter another string:
name2
2
name2
name2