gpt4 book ai didi

c - 将结构传递给函数

转载 作者:太空狗 更新时间:2023-10-29 16:18:58 24 4
gpt4 key购买 nike

我是一名新的 C 程序员,我想知道如何将 struct 传递给函数。我遇到错误,无法找出正确的语法来执行此操作。这是它的代码....

结构:

struct student{
char firstname[30];
char surname[30];
};

struct student person;

调用:

addStudent(person);

原型(prototype):

void addStudent(struct student);

和实际功能:

void addStudent(person)
{
return;
}

编译器错误:

line 21: warning: dubious tag declaration: struct student
line 223: argument #1 is incompatible with prototype:

最佳答案

这是通过引用传递 struct 的方法。这意味着您的函数可以在函数外部访问 struct 并修改其值。为此,您可以将指向结构的指针传递给函数。

#include <stdio.h>
/* card structure definition */
struct card
{
int face; // define pointer face
}; // end structure card

typedef struct card Card ;

/* prototype */
void passByReference(Card *c) ;

int main(void)
{
Card c ;
c.face = 1 ;
Card *cptr = &c ; // pointer to Card c

printf("The value of c before function passing = %d\n", c.face);
printf("The value of cptr before function = %d\n",cptr->face);

passByReference(cptr);

printf("The value of c after function passing = %d\n", c.face);

return 0 ; // successfully ran program
}

void passByReference(Card *c)
{
c->face = 4;
}

这是按值传递 struct 的方式,以便您的函数接收 struct 的副本并且无法访问外部结构来修改它。我所说的外部是指在功能之外。

#include <stdio.h>


/* global card structure definition */
struct card
{
int face ; // define pointer face
};// end structure card

typedef struct card Card ;

/* function prototypes */
void passByValue(Card c);

int main(void)
{
Card c ;
c.face = 1;

printf("c.face before passByValue() = %d\n", c.face);

passByValue(c);

printf("c.face after passByValue() = %d\n",c.face);
printf("As you can see the value of c did not change\n");
printf("\nand the Card c inside the function has been destroyed"
"\n(no longer in memory)");
}


void passByValue(Card c)
{
c.face = 5;
}

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

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