我有一个用C编写的控制台应用程序,它接受用户的输入以操作链表.
当用户输入"Add"来添加一个项目时,它将添加该项目,但以这种方式添加的所有 node 都将共享使用"Add"命令创建的最后一个项目的名称.
list.h个
typedef struct node {
char *name;
int value;
struct node *next;
} node_js;
static node_js *currentNode;
void printList(node_js *thing) {
currentNode = thing;
while (currentNode != NULL) {
printf("%s\n", currentNode->name);
printf(">%d\n", currentNode->value);
currentNode = currentNode->next;
}
printf("\n");
}
void addLast(node_js **thing, const char *name, int val) {
if (*thing == NULL) {
*thing = (node_js *)malloc(sizeof(node_js));
//(*thing)->name = name;
(*thing)->name = name;
(*thing)->value = val;
(*thing)->next = NULL;
} else {
currentNode = *thing;
while (currentNode->next != NULL) {
currentNode = currentNode->next;
}
currentNode->next = (node_js *)malloc(sizeof(node_js));
//currentNode->next->name = strdup(name);
currentNode->next->name = name;
currentNode->next->value = val;
currentNode->next->next = NULL;
}
}
void removeLast(node_js **thing) {
if (*thing == NULL) {
return;
}
if ((*thing)->next == NULL) {
free(*thing);
*thing = NULL;
return;
}
currentNode = *thing;
while (currentNode->next->next != NULL) {
currentNode = currentNode->next;
}
free(currentNode->next);
currentNode->next = NULL;
}
main.c
//the problem is on the addLast() inside the while(1), the probelm only occur with items that are
//added when user inputs "add"
#include <stdio.h>
#include <stdlib.h>
#include "list.h"
static int numInput;
static char textInput[32];
static char uInput[16];
node_js *list = NULL;
int main() {
printf("--- Welcome to the program! ---\n>Type 'exit', 'quit' or 'q' to exit\n>Type 'help' for a list of the commands\n\n");
//make list
list = (node_js *)malloc(sizeof(node_js));
list->name = "joe";
list->value = 10;
list->next = (node_js *)malloc(sizeof(node_js));
list->next->name = "james";
list->next->value = 20;
list->next->next = NULL;
addLast(&list, "jane", 30); //here it works fine
while (1) {
printf("input: ");
scanf_s("%s", textInput, sizeof(textInput));
if (strcmp(textInput, "quit") == 0 || strcmp(textInput, "q") == 0 || strcmp(textInput, "exit") == 0) {
printf("Bye!");
free(list);
exit(1);
}
if (strcmp(textInput, "print") == 0) {
printList(list);
}
if (strcmp(textInput, "add") == 0) {
printf("name: ");
scanf_s("%s", uInput, sizeof(uInput));/*the problem is on the addLast() inside the while(1), the probelm only occur with items that are added when user inputs "add"*/
printf("number: ");
scanf_s("%d", &numInput, sizeof(numInput));
addLast(&list, uInput, numInput);
printf("--- added (%s, %d) ---\n", uInput, numInput);
}
if (strcmp(textInput, "remove") == 0) {
removeLast(&list);
printf("--- Removed last item of list ---\n");
}
}
free(list);
return 0;
}
我没有使用textInput
来扫描用户输入,而是try 为此创建另一个array.在这方面找不到任何东西,也试图询问ChatGPT,但没有帮助.