【问题标题】:How give value to structures in c? [duplicate]如何为c中的结构赋予价值? [复制]
【发布时间】:2020-08-11 13:20:12
【问题描述】:

我正在使用 c 中的结构,但我无法为结构的属性赋予价值。

#include <stdio.h>
#include <string.h>

struct Book{
        char name[10];
        int id;
};

int main(){
        char tmp_name[10];
        int tmp_id;
        for(;;){
                struct Book a;
                scanf("%s",tmp_name);
                scanf("%d", tmp_id);
                strcpy(a.name,tmp_name);
                a.id = tmp_id;
                printf("name: %s\nid:%d", a.name, a.id);
        }

        return 0;
}

此代码编译正确但出现Segmentation fault (core dumped) 错误。

【问题讨论】:

  • for(;;)...为什么要创建无限循环?
  • scanf("%d", tmp_id); ==> scanf("%d", &amp;tmp_id); 或者,更好的是 if (scanf("%d", &amp;tmp_id) != 1) exit(EXIT_FAILURE); 甚至最好的是 char line[1000]; if (!fgets(line, sizeof line, stdin) exit(EXIT_FAILURE); if (sscanf(line, "%d", &amp;tmp_id) != 1) exit(EXIT_FAILURE);
  • ...这与结构无关。
  • scanf("%s" ==> scanf("%9s" 或更好:使用fgets 而不是scanf
  • 不需要tmp_nametmp_idscanf("%d", &amp;tmp_id); ==> scanf("%d",&amp;(a.id));

标签: c struct


【解决方案1】:

你写:

这段代码编译正确...

在这种情况下,我强烈建议您提高编译器的警告级别。

例如“gcc -Wall code.c”可能会给你一个警告:

In function 'main':
warning: format '%d' expects argument of type 'int *', but argument 2 has type 'int' [-Wformat=]
   15 |                 scanf("%d", tmp_id);
      |                        ~^   ~~~~~~
      |                         |   |
      |                         |   int
      |                         int *

它告诉你一切,即 你将一个 int 传递给一个期望一个 int 指针的函数

所以只需传递一个 int 指针,例如:

scanf("%d", &tmp_id);
            ^
            Take address of tmp_id so that you have a pointer

顺便说一句:对于 gcc,您可以使用 -Werror 以便将所有警告视为错误

【讨论】:

    【解决方案2】:

    你可以直接给struct赋值。您不需要其他变量。

    struct Book a
    scanf("%s", a.name);
    scanf("%d", &a.id);
    printf("name: %s\nid:%d", a.name, a.id);
    

    【讨论】:

    • scanf("%s", a.name) 不提供针对缓冲区溢出漏洞的保护,在这方面与gets 函数没有什么不同。必须改用scanf("%9s", a.name)
    【解决方案3】:

    scanf("%d", tmp_id); 必须是 scanf("%d", &amp;tmp_id);

    【讨论】:

      【解决方案4】:

      使用scanf时需要通过引用传入。

              scanf("%s", tmp_name);
              scanf("%d", &tmp_id);
      

      【讨论】:

      • 我认为char 类型不需要&amp;
      • @AmirrezaRiahi 我同意,这种方式会使初学者对 C 数组的实际工作方式产生错误的理解。但我认为这不是“char 类型”,而是数组。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-08
      • 2021-02-23
      相关资源
      最近更新 更多