我每次添加链接列表后都会打印它。问题是它只打印最近添加的节点。用户应该输入用于创建节点的字符串,然后将该节点添加到列表中。这是代码:
int main() {
char userChoice = printMenu();
int setNumber;
while (userChoice != 'q') {
printf("set: ");
scanf("%d", &setNumber);
Node **nodeArray;
nodeArray = malloc(10 * sizeof(Node *));
int i;
for (i = 0; i < 10; i++) {
nodeArray[i] = malloc(sizeof(Node));
}
if (userChoice == 'a')
add(&nodeArray, setNumber);
else
printf("Please enter a valid menu option.");
//printf("%s\n", (nodeArray[setNumber]->next)->data);
userChoice = printMenu();
}
void add(Node ***nodeArray, int setNumber) {
char userString[5];
printf("Please enter some data: ");
scanf("%s", userString);
Node *head = *nodeArray[setNumber]; /* head pointer to first element of array (dummy) */
Node *newNode = malloc(sizeof(Node)); /* new node to be added to array */
strncpy(newNode->data, userString, sizeof(newNode->data)); /* copies string entered by the user to data field of new node */
newNode->next = NULL; /* initializes next field of new node to NULL */
while (head->next)
head = head->next; /* points head to next element in list */
head->next = newNode; /* adds element to list */
head = *nodeArray[setNumber]; /* points head back to start of list */
Node *tmp = head;
printf("List is: ");
while (tmp->next) {
printf("%s", tmp->data);
tmp = tmp->next;
}
}
举个例子,当我输入“one”时,它打印出“one”。然后,当我添加“两个”时,它只打印出两个而不是打印出“一个两个”。我做错了什么?
答案 0 :(得分:1)
此*nodeArray[setNumber]
表示*(nodeArray[setNumber])
,但您似乎是(*nodeArray)[setNumber]
。或者更好的是,不要将&nodeArray
传递给add()
,只需通过nodeArray
即可。所以:
add(nodeArray, setNumber);
...
void add(Node **nodeArray, int setNumber) {
...
Node *head = nodeArray[setNumber];
答案 1 :(得分:0)
问题是每次进入循环时都会创建一个新的内存块。剪切并粘贴在循环外部创建数组的代码,一切都应该正常工作。