【问题标题】:passing structure variable to function将结构变量传递给函数
【发布时间】:2015-02-12 23:20:36
【问题描述】:

我正在研究 C 编程中的结构。但是,我对这段代码感到困惑,所以我不明白。函数中的b 来自哪里?怎么会是这样使用的结构?你能给我解释一下吗? 我们可以说display(struct book b1) ;调用函数吗?感谢所有感谢的回答。

#include <stdio.h>

struct book
{
    char name[25] ;
    char author[25] ;
    int callno ;
} ;
int main()
{
    struct book b1 = { "Let us C", "YPK", 101 } ;
    display ( b1 ) ;

    return 0;
}

void display ( struct book b )
{
    printf ( "\n%s %s %d", b.name, b.author, b.callno ) ;
}

【问题讨论】:

  • void display (int i) { ... }有什么问题吗?
  • 你能解释一下为什么不能吗?
  • 我们可以说struct book b1 ; 调用函数吗?
  • 我还是不明白你的困惑。
  • bdisplay()中的值参数自动变量,调用时从b1中复制main()。真的就是这么简单。那你不明白怎么办? (并且可能与您的问题有关,您(更好)得到的关于 display() 的警告在使用前没有被声明并且具有假定的 int 返回值,并且当您最终遇到它时不匹配该隐式声明,可以修复通过对display 进行适当的原型设计或将其定义移动到上方 main())。

标签: c arrays function struct


【解决方案1】:

我最好的猜测是,你被 main b1 中的变量名和函数 b 中的参数名的相似性弄糊涂了。这些名字是完全不相关的,可以随便叫什么。

main 函数中,b1 是一个局部变量,被声明为struct book 类型,然后使用编译时常量初始化器进行初始化。 b1 的名称是任意的,可以是任何有效的标识符。

display 函数中,bstruct book 类型函数的参数。调用函数时,调用者必须提供struct book,并且该结构将复制b。重要的是要了解b 是传递给display 函数的结构的副本,这意味着b 对其本地副本所做的任何更改都不会传播到@987654335 中声明的原始结构@。

这里尝试在代码中演示这些原则

#include <stdio.h>

struct book
{
    char name[25] ;
    char author[25] ;
    int callno ;
};

void display( struct book someArbitraryNameForTheLocalCopyOfTheStructThatThisFunctionUses )
{
    printf ( "%s  ", someArbitraryNameForTheLocalCopyOfTheStructThatThisFunctionUses.name   );
    printf ( "%s  ", someArbitraryNameForTheLocalCopyOfTheStructThatThisFunctionUses.author );
    printf ( "%d\n", someArbitraryNameForTheLocalCopyOfTheStructThatThisFunctionUses.callno );

    // the following line has no effect on the variable in main since
    // all we have here is a local copy of the structure
    someArbitraryNameForTheLocalCopyOfTheStructThatThisFunctionUses.callno = 5555;
}

int main()
{
    struct book someLocalVariable = { "Let us C", "YPK", 101 };

    // the following line will make a copy of the struct for the 'display' function
    display( someLocalVariable );

    // the following line will still print 101, since the 'display' function only changed the copy
    printf ( "%d\n", someLocalVariable.callno );

    struct book anotherBook = { "Destiny", "user3386109", 42 };

    // any variable of type 'struct book' can be passed to the display function
    display( anotherBook );

    return 0;
}

【讨论】:

    【解决方案2】:

    b 是显示函数的参数名称。这是你必须传递给它的。所以在调用 display(b1); 时的主函数中; display函数中的b代表main函数中b1定义的书本结构。

    【讨论】:

      【解决方案3】:

      传递结构就像传递任何其他类型一样:该函数需要一个struct b 类型的变量作为它的参数,然后它就可以使用它。幕后发生的事情是,您主要功能中b1 的所有数据都复制到您的显示功能的b 中。因此请注意:当您更改displayb 成员的值时,它不会更改mainb1 的值。如果你想让这种情况发生,你必须传递一个指针。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-01-12
        • 1970-01-01
        • 2012-05-09
        • 2020-01-16
        • 2020-07-28
        相关资源
        最近更新 更多