gpt4 book ai didi

c - 将结构变量传递给函数

转载 作者:太空宇宙 更新时间:2023-11-04 08:32:51 25 4
gpt4 key购买 nike

我正在研究 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 ) ;
}

最佳答案

我最好的猜测是,您对 main b1 中的变量名称与函数 b 中的参数名称的相似性感到困惑。这些名字完全不相关,可以随便叫。

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

display 函数中,bstruct book 类型函数的参数。调用该函数时,调用者必须提供一个struct book,该结构将被复制b。重要的是要了解 b 是传递给 display 函数的结构的副本,这意味着 b 对它的本地副本不会传播到 main 中声明的原始结构。

下面是尝试在代码中演示这些原则

#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;
}

关于c - 将结构变量传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27474280/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com