如何将结构短名称的变量地址传递给函数
How to pass the variable address of the structure short name to a function
如何将结构短名称 (color
) 的变量地址传递给函数 (fun
) 参数。
#include <stdio.h>
void fun();
struct figure {
char name[30];
float field;
} color;
int main(void) {
fun();
return 0;
}
struct figure { ... };
只会引入一个名为 struct figure
的新类型,而 struct figure { ... } color;
会做两件事(1)引入上述类型和(2)定义一个名为 [=15 的变量=] 那种类型的。
要将类型为 struct figure
的对象传递给函数,请编写...
struct figure{
char name[30];
float field;
} color;
void fun(struct figure f) {
printf("%s %f\n", f.name, f.field);
}
int main(void){
struct figure myObj;
strcpy(myObj.name, "Hello!");
myObj.field = 1.0;
fun(myObj);
return 0;
}
您还可以传递此类对象的地址,这样函数也可以更改最初传递的对象:
void fun(struct figure *f) {
f->field = 2.0
printf("%s %f\n", f->name, f->field);
}
int main() {
...
fun(&myObj);
How to pass the variable address of the structure short name
传递地址只需要&color
.
然后函数需要接受一个指向结构图的指针。
它可能看起来像:
#include <stdio.h>
#include <string.h>
struct figure{
char name[30];
float field;
} color;
void fun(struct figure *); // Function takes pointer to struct figure
int main(void){
strcpy(color.name, "Joe"); // Initialize color
color.field = 42.0;
fun(&color); // Pass address of color
return 0;
}
void fun(struct figure *c)
{
printf("%s\n", c->name); // Access color using the passed pointer
printf("%f\n", c->field);
}
输出:
Joe
42.000000
如何将结构短名称 (color
) 的变量地址传递给函数 (fun
) 参数。
#include <stdio.h>
void fun();
struct figure {
char name[30];
float field;
} color;
int main(void) {
fun();
return 0;
}
struct figure { ... };
只会引入一个名为 struct figure
的新类型,而 struct figure { ... } color;
会做两件事(1)引入上述类型和(2)定义一个名为 [=15 的变量=] 那种类型的。
要将类型为 struct figure
的对象传递给函数,请编写...
struct figure{
char name[30];
float field;
} color;
void fun(struct figure f) {
printf("%s %f\n", f.name, f.field);
}
int main(void){
struct figure myObj;
strcpy(myObj.name, "Hello!");
myObj.field = 1.0;
fun(myObj);
return 0;
}
您还可以传递此类对象的地址,这样函数也可以更改最初传递的对象:
void fun(struct figure *f) {
f->field = 2.0
printf("%s %f\n", f->name, f->field);
}
int main() {
...
fun(&myObj);
How to pass the variable address of the structure short name
传递地址只需要&color
.
然后函数需要接受一个指向结构图的指针。
它可能看起来像:
#include <stdio.h>
#include <string.h>
struct figure{
char name[30];
float field;
} color;
void fun(struct figure *); // Function takes pointer to struct figure
int main(void){
strcpy(color.name, "Joe"); // Initialize color
color.field = 42.0;
fun(&color); // Pass address of color
return 0;
}
void fun(struct figure *c)
{
printf("%s\n", c->name); // Access color using the passed pointer
printf("%f\n", c->field);
}
输出:
Joe
42.000000