【问题标题】:Returning a structure results in gibberish返回结构会导致乱码
【发布时间】:2022-01-08 07:56:13
【问题描述】:

我在 C 中使用结构,当我尝试从函数返回结构时,当我尝试在 main.js 中打印该结构的内容时,总是会导致乱码。 这是我的代码:

#include <stdio.h>
struct etudiant
{
    int a;
    int b;
    int c;
};
typedef struct etudiant ETD;

ETD ajouter_etd()
{
    ETD e;
    scanf("%i%i%i", e.a, e.b, e.c);
    return e;
}

void main()
{
    ETD e;
    e = ajouter_etd();
    printf("%i%i%i", e.a, e.b, e.c);
}

【问题讨论】:

  • 当你编译时启用了警告,你得到了什么警告?
  • @Dhia Ammar 使用 scanf("%i%i%i", &e.a, &e.b, &e.c);
  • 用最近调用的GCC 编译你的代码gcc -Wall -Wextra -g

标签: c function struct structure


【解决方案1】:

您必须将变量的地址传递给scanf,因为它需要知道将其转换结果放在内存中的哪个位置。这是通过address-of operator (&amp;) 完成的。

#include <stdio.h>

typedef struct etudiant {
    int a;
    int b;
    int c;
} ETD;

ETD ajouter_etd(void)
{
    ETD e;
    scanf("%i%i%i", &e.a, &e.b, &e.c);
    return e;
}

int main(void)
{
    ETD e;
    e = ajouter_etd();
    printf("%i%i%i\n", e.a, e.b, e.c);
}

【讨论】:

    猜你喜欢
    • 2022-01-08
    • 2019-02-26
    • 1970-01-01
    • 2016-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多