我是一名新 C 程序员,我想知道如何通过struct
到一个函数。我收到错误并且无法找出正确的语法来执行此操作。这是它的代码......
Struct:
struct student{
char firstname[30];
char surname[30];
};
struct student person;
Call:
addStudent(person);
原型:
void addStudent(struct student);
和实际功能:
void addStudent(person)
{
return;
}
编译器错误:
第 21 行:警告:可疑标签声明:struct Student
第 223 行:参数 #1 与原型不兼容:
这是如何通过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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)