开发者

Problem with scanf loading struct -> char[]

I'm dealing with this issue: I've been creating linked list (using a structure) and I want to load input from use开发者_如何学Cr. When I debug this code, the debugger stop on the line of scanf.

typedef struct Person{
char name[64];
int number;
} Person;

Person* record = malloc(sizeof(Person));
printf("Input name: \n");
scanf("%63s", record->name);

I know that (*record).number == record->number and '&' is used to get an adress of variable but I have no idea how to solve my problem in the simplest way if I want to use scanf for loading input.

Thanks in advance.


When a program is debugged using gdb and a scanf statement is encountered, the debugger will prompt for user input. If you give the input at that point and hit Enter, the execution will continue.

For eg., 1. If the source code is the following in a file name 'llist.c'

#include <stdio.h>
#include <stdlib.h>

typedef struct Person{
char name[64];
int number;
} Person;

int main()
{

    Person* record = malloc(sizeof(Person));
    if(record == NULL)
    {
       printf("Memory allocation failed\n");
       return;
    }
    printf("Input name: \n");
    scanf("%63s", record->name);
    printf("Name %s\n", record -> name);
    return 0;
}

Compile it using the debug option as

gcc -g -o list llist.c

  1. Run the debugger as gdb ./list and enter the command run to start the program execution.
  2. When prompted for input, enter any string and hit Enter.
  3. The string is then printed to the terminal.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜