【问题标题】:scanf of struct makes program crashstruct的scanf使程序崩溃
【发布时间】:2018-11-07 16:18:07
【问题描述】:

这是代码。函数“leggi”应该读取 c[i].a 的值,但是当我在控制台中输入第一个数字时,程序崩溃了。 这可能是一个指针问题,但我无法弄清楚

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

typedef struct cane{
    int a;
}cane;

void leggi(cane *c[20]){
    int i;
    for(i=0;i<5;i++)
        scanf("%d", &c[i]->a );
}

int main(){
    int i;
    cane c[20];

    leggi(&c);

    for(i=0;i<5;i++)
        printf("%d",c[i].a);

    return 0;
}

【问题讨论】:

  • &amp;c 是指向cane[20] 的指针。 cane *c[20] 是一个包含 20 个指向 cane 的指针的数组。
  • 对于C 中的数组,数组名称c 已经是一个指针,因此无需将&amp;c 传递给leggi(...)
  • GCC 说:error: passing argument 1 of ‘leggi’ from incompatible pointer type [-Werror=incompatible-pointer-types] —— leggi(&amp;c); —— note: expected ‘cane **’ {aka ‘struct cane **’} but argument is of type ‘cane (*)[20]’ {aka ‘struct cane (*)[20]’}
  • 好的,谢谢! @cleblanc
  • @cleblanc c不是指针。但它确实衰减为指针。

标签: c pointers struct crash


【解决方案1】:

您将错误的类型传递给函数。

如果要将数组传递给函数,则数组名称会衰减为指向其第一个元素的指针,因此参数只是指向类型的指针:

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

typedef struct cane{
    int a;
}cane;

void leggi(cane *c){
    int i;
    for(i=0;i<5;i++)
        scanf("%d", &(c[i].a) );
}

int main(){
    int i;
    cane c[20];

    leggi(c);

    for(i=0;i<5;i++)
        printf("%d",c[i].a);

    return 0;
}

【讨论】:

  • 为什么&amp;(c[i].a)中的括号?
  • @JonathanLeffler 它们不是必需的,但我认为阅读起来可能更清晰。
【解决方案2】:

&amp;c 的类型是cane (*)[20],即指向数组的指针。您已将函数的参数声明为 cane *[20],它是(作为函数参数)cane**,它是指向指针的指针。

您可能打算改为传递指向数组元素的指针:

void leggi(cane *c)
    // ...
    scanf("%d", &c[i].a );

//
leggi(c);

或者您可能真的打算将指针传递给数组:

void leggi(cane (*c)[20])
    scanf("%d", &(*c)[i].a )

//
leggi(&c);

【讨论】:

    猜你喜欢
    • 2016-06-01
    • 2012-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-17
    • 2014-06-24
    • 1970-01-01
    相关资源
    最近更新 更多