This is how to pass the struct
by reference. This means that your function can access the struct
outside of the function and modify its values. You do this by passing a pointer to the structure to the function.
#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
", c.face);
printf("The value of cptr before function = %d
",cptr->face);
passByReference(cptr);
printf("The value of c after function passing = %d
", c.face);
return 0 ; // successfully ran program
}
void passByReference(Card *c)
{
c->face = 4;
}
This is how you pass the struct
by value so that your function receives a copy of the struct
and cannot access the exterior structure to modify it. By exterior I mean outside the function.
#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
", c.face);
passByValue(c);
printf("c.face after passByValue() = %d
",c.face);
printf("As you can see the value of c did not change
");
printf("
and the Card c inside the function has been destroyed"
"
(no longer in memory)");
}
void passByValue(Card c)
{
c.face = 5;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…