scanf_s抛出异常

Ton*_*ion 3 windows exception visual-c++

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

这绝不代表完整的链表实现.

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

编辑:更新后的代码与建议的解决方案,但仍获得了AccessViolationException第一之后scanf_s

码:

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);

...
Run Code Online (Sandbox Code Playgroud)

shf*_*301 5

您使用的scanf_s参数不正确.请查看MSDN文档中有关该函数的示例.它要求您在缓冲区之后为所有字符串或字符参数传递缓冲区的大小.所以

result = scanf_s("%s", temp->name); 
Run Code Online (Sandbox Code Playgroud)

应该:

 result = scanf_s("%s", temp->name, 20);
Run Code Online (Sandbox Code Playgroud)

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

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