【问题标题】:Passing parameters struct to function in C将参数结构传递给C中的函数
【发布时间】:2018-05-29 18:36:16
【问题描述】:

我是系统分析师和开发人员学生,我正在尝试编写代码,但我被卡住了,结构和函数很容易理解,但是将两者一起使用......是一个......废话......

我做错了什么?

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

typedef struct mercearia
{
    char mercadoria[20];
    int quantidade;
    int valor;

} mercearia;

void EstruturaCadastro(struct mercearia *m)
{
    int i;

    for(i = 0; i < 5; i++)
    {
        printf("\n");

        setbuf(NULL, stdin);
        printf("Insira nome do produto a cadastrar: ");
        scanf("%s", &(*m)[i].mercadoria);

        setbuf(NULL, stdin);
        printf("Insira a quantidade do produto: ");
        scanf("%i", &(*m)[i].quantidade);

        setbuf(NULL, stdin);
        printf("Insira o valor do produto: R$ ");
        scanf("%i", &(*m)[i].valor);
    }
}
    int main(void)
    {
        setlocale(LC_ALL, "");
        struct mercearia m[5];
        EstruturaCadastro(&m);
    }

它给了我巨大的错误列表。然后我编写了相同的代码,但没有创建结构数组,并且代码运行良好。我错过了一些东西。

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

typedef struct mercearia
{
    char mercadoria[20];
    int quantidade;
    int valor;

} mercearia;


void EstruturaCadastro(struct mercearia *x)
{
    printf("\n");

    printf("Insira nome do produto: ");
    scanf("%s", &(*x).mercadoria);setbuf(NULL, stdin);

    printf("Insira a quantidade do produto: ");
    scanf("%i", &(*x).quantidade);setbuf(NULL, stdin);

    printf("Insira o valor do produto: R$ ");
    scanf("%i", &(*x).valor);setbuf(NULL, stdin);
}

    int main(void)
    {
        setlocale(LC_ALL, "");
        struct mercearia produto;

        EstruturaCadastro(&produto);
    }

【问题讨论】:

  • 我从不相信自己有运算符优先级,我会在这里更慷慨地使用()&amp;(*m)[i].mercadoria
  • 这与结构无关,而与您如何将数组传递给函数有关。要使该代码正常工作,应将参数声明为 mercearia (*m)[5]
  • 您可能需要接受指导tour。它是pittoresque。
  • 您可以在mercadoria 字段中使用m[i] 而不是&amp;(*m)[i],在其他两个字段中使用&amp;m[i] 而不是&amp;(*m)[i]
  • 或者,您可以更改函数参数而不是参数类型。在您的第一个版本中传递 m 而不是 &amp;m

标签: c function struct parameter-passing


【解决方案1】:

在尝试第一个示例(更难)之前,您需要了解第二个示例(简单)

void EstruturaCadastro(struct mercearia *x)
{
    printf("\n");

    printf("Insira nome do produto: ");
    scanf("%s", x->mercadoria);

    printf("Insira a quantidade do produto: ");
    scanf("%i", &x->quantidade);

    printf("Insira o valor do produto: R$ ");
    scanf("%i", &x->valor);
}

无需setbuf() 调用,按键时刷新标准输入

完成此操作后,您可以在第一个示例中更改为 m[i]-&gt;mercadoria 等。

【讨论】:

    【解决方案2】:

    你原来的功能有各种错误。您正在向它传递一个指向 struct mercearia 的指针,这对于传入您的数组来说很好。在函数内部,您可以像对待数组一样对待 m,例如,m[0].valor 是您访问第一个元素的 valor 值的方式。

    这意味着你对scanf的各种调用变成了

        scanf("%s", m[i].mercadoria);
        scanf("%i", &m[i].quantidade);
        scanf("%i", &m[i].valor);
    

    请注意,与其他数据类型不同,要读取字符串,您不需要传递指向字符串的指针,因此您不需要前面的 &amp;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-12
      • 2015-01-03
      相关资源
      最近更新 更多