Scanf_s throws exception

Why the following code throws an exception when moving to the second scanf_safter entering a number to place in the structure.

This in no way means implementing a complete linked list.

Not sure how to go to the next scanf_swhen entering a value? Any ideas?

EDIT: Updated code with the proposed solution, but still get it AccessViolationExceptionafter the firstscanf_s

the code:

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

...
+3
source share
5 answers

You need

result = scanf_s("%d", &temp->age);

and

result = scanf_s("%f", &temp->height);

The reason is that sscanf(and friends) require a pointer to the output variable so that it can save the result there.

, temp . ( , ), , :

int FillInLinkedList(node** temp)

, , .

+3

scanf_s . MSDN . , .

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

:

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

scanf_s - , , , .

, scanf_s - , , scanf_s.

+5

scanf() , ( )
:

char string[10];
int n;
scanf("%s", string); //string actually points to address of
                     //first element of string array
scanf("%d", &n); // &n is the address of the variable 'n'
+2
  • %19c %s

  • temp->age &temp-age

  • temp->height &temp->height

+1

, scanf() . .. & temp- > age

temp-age , .

+1

Source: https://habr.com/ru/post/1734759/


All Articles