gpt4 book ai didi

c - 程序执行停止在 scanf?

转载 作者:行者123 更新时间:2023-12-04 12:18:57 26 4
gpt4 key购买 nike

main.c(包含所有头文件,如 stdio、stdlib 等):

int main()
{
int input;

while(1)
{
printf("\n");
printf("\n1. Add new node");
printf("\n2. Delete existing node");
printf("\n3. Print all data");
printf("\n4. Exit");
printf("Enter your option -> ");
scanf("%d", &input);

string key = "";
string tempKey = "";
string tempValue = "";
Node newNode;
Node temp;
switch (input) {
case 1:
printf("\nEnter a key: ");
scanf("%s", tempKey);
printf("\nEnter a value: ");
scanf("%s", tempValue); //execution ternimates here

newNode.key = tempKey;
newNode.value = tempValue;

AddNode(newNode);
break;
case 2:
printf("\nEnter the key of the node: ");
scanf("%s", key);
temp = GetNode(key);
DeleteNode(temp);
break;
case 3:
printf("\n");
PrintAllNodes();
break;
case 4:
exit(0);
break;
default:
printf("\nWrong option chosen!\n");
break;
}
}

return 0;
}

存储.h:

#ifndef DATABASEIO_H_
#define DATABASEIO_H_

//typedefs
typedef char *string;

/*
* main struct with key, value,
* and pointer to next struct
* Also typedefs Node and NodePtr
*/
typedef struct Node {
string key;
string value;
struct Node *next;
} Node, *NodePtr;

//Function Prototypes
void AddNode(Node node);
void DeleteNode(Node node);
Node GetNode(string key);
void PrintAllNodes();

#endif /* DATABASEIO_H_ */

我正在使用 Eclipse CDT,当我输入 1 时,我会输入一个 key 。然后控制台说。我使用了 gdb 并得到了这个错误:

Program received signal SIGSEGV, Segmentation fault.
0x00177024 in _IO_vfscanf () from /lib/tls/i686/cmov/libc.so.6

有什么想法吗?

最佳答案

你应该为你的字符串(typedef char* string)分配足够的内存以使用 scanf() 读入

关于c - 程序执行停止在 scanf?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2662614/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com