【问题标题】:Problem with scanf loading struct -> char[]scanf 加载结构的问题 -> char[]
【发布时间】:2011-08-04 15:44:26
【问题描述】:

我正在处理这个问题: 我一直在创建链表(使用结构),我想从用户那里加载输入。 当我调试这段代码时,调试器停止在 scanf 行。

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

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

我知道 (*record).number == record->number 和 '&' 用于获取变量的地址,但如果我想使用 scanf,我不知道如何以最简单的方式解决我的问题用于加载输入。

提前致谢。

【问题讨论】:

  • 没有调试器能用吗?
  • 似乎工作..根据我。
  • 不只是调试器在等待你的输入?
  • 我在 Windows 7 中使用 Eclipse,当我运行程序时,它正在运行并且永不停止。 printf 不打印任何东西(因为代码肯定有错误)。
  • @John Bode:如下所述,Eclipse 环境肯定有一些意外行为,因为其他代码是正确的。

标签: c arrays struct char scanf


【解决方案1】:

当使用 gdb 调试程序并遇到 scanf 语句时,调试器将提示用户输入。如果您在该点输入并按 Enter,则执行将继续。

例如, 1.如果源代码在文件名'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;
}

使用调试选项编译它

gcc -g -o list llist.c

  1. gdb ./list运行调试器并输入命令run开始程序执行。
  2. 当提示输入时,输入任意字符串并按 Enter。
  3. 然后将字符串打印到终端。

【讨论】:

  • 您好,这可行,但是当我尝试在 Eclipse 中运行或调试同一程序时,它不起作用!同样的问题。所以我认为Eclipse和Win之间一定有问题..
猜你喜欢
  • 1970-01-01
  • 2012-07-10
  • 2019-09-15
  • 2013-12-12
  • 1970-01-01
  • 2017-07-21
  • 1970-01-01
  • 2015-11-22
  • 1970-01-01
相关资源
最近更新 更多