【问题标题】:C - passing structure + members by valueC - 按值传递结构+成员
【发布时间】:2015-01-21 14:26:37
【问题描述】:

我的问题似乎总是关于使用函数。它仍然让我感到困惑!在这个教科书练习中,我被要求通过值传递一个结构,然后调整它并通过引用传递。最初,我设计代码以在 main 中完成所有工作。现在我按价值传递。所以我添加了新函数,我认为我正确地传递了结构,但我在行出现错误 void function1(struct Inventory inv){ 告诉我参数 1 (inv) 的类型不完整。请帮忙!

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

void function1(struct Inventory inv);

struct Inventory{
    char name[20];
    int number;
    float price;
    float total;
} 

void main(){

    items;

    void function1(items);

    float total = items.number*items.price;
    printf("Item\tNumber\tPrice\tTotal\tAddress of number\n");
    printf("%s\t%d\t%.2f\t%.2f\t%X\n\n",items.name,items.number,items.price,total,&items.number);

    getch();
}

void function1(struct Inventory inv) {

    printf("Enter the name of the item: ");
    scanf("%s", inv.name);

    printf("Enter the number of items: ");
    scanf("%d", &inv.number);

    printf("Enter the price of each item: ");
    scanf("%f", &inv.price);
}

【问题讨论】:

  • 这是您在本网站上的第三个问题。在您发布更多内容之前,请学会缩进您的代码
  • 通过值传递任何非原始类型是低效且毫无意义的。学习使用指针。
  • 我的猜测是它教会了我按值传递和按引用传递之间的区别。尽管指针是最好的方法。
  • 我建议您首先编译并运行一个使用结构但没有函数的程序。然后开始构建一个接受结构参数的函数。
  • 这正是我所做的,但我无法理解如何在结构的上下文中实现这一点。对于常规变量,我对函数的理解足够好,但对于结构,它让我感到困惑

标签: c structure argument-passing


【解决方案1】:

在函数原型中使用它之前,你必须定义你的结构。

struct Inventory{
char name[20];
int number;
float price;
float total;
}items;

void function1(struct Inventory inv);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-24
    • 2012-10-06
    • 2014-12-15
    • 2012-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-08
    相关资源
    最近更新 更多