gpt4 book ai didi

windows - scanf_s 抛出异常

转载 作者:可可西里 更新时间:2023-11-01 14:40:23 25 4
gpt4 key购买 nike

为什么在输入要放入结构的数字后到达第二个 scanf_s 时,以下代码会抛出异常。

这绝不代表一个完整的链表实现。

输入值后不确定如何进入下一个scanf_s?有什么想法吗?

编辑:使用建议的解决方案更新了代码,但在第一个 scanf_s

之后仍然得到 AccessViolationException

代码:

struct node
{
char name[20];
int age;
float height;
node *nxt;
};

int FillInLinkedList(node* temp)
{

int result;
temp = new node;

printf("Please enter name of the person");
result = scanf_s("%s", temp->name);

printf("Please enter persons age");
result = scanf_s("%d", &temp->age); // Exception here...

printf("Please enter persons height");
result = scanf_s("%f", &temp->height);

temp->nxt = NULL;
if (result >0)
return 1;
else return 0;
}

// calling code

int main(array<System::String ^> ^args)
{
node temp;

FillInLinkedList(&temp);

...

最佳答案

您正在使用参数不正确的 scanf_s。查看 MSDN documentation 中的示例为功能。它要求您在所有字符串或字符参数的缓冲区之后传入缓冲区的大小。所以

result = scanf_s("%s", temp->name); 

应该是:

 result = scanf_s("%s", temp->name, 20);

第一次调用 scanf_s 是从堆栈中读取垃圾,因为它正在寻找另一个参数并可能破坏内存。

没有编译器错误,因为 scanf_s 使用可变参数列表 - 该函数没有固定数量的参数,因此编译器不知道 scanf_s 期望什么。

关于windows - scanf_s 抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2350849/

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