gpt4 book ai didi

c - 从结构返回值

转载 作者:行者123 更新时间:2023-12-02 05:32:15 24 4
gpt4 key购买 nike

typedef struct Value{
int id;
char type;
char a;
} Value;

void fooV(Value v){
v.id = 10;
v.type = 'L';
v.a = 'R';
}

int main(void){
Value v;
Pointer p;
int id = 5;
char type = 't';
char a = 'a';

printf("id: %d, type: %c, a: %c \n",id,type,a);

v.a = a;
v.id = id;
v.type = type;
fooV(v);
printf("id: %d, type: %c, a: %c \n",id,type,a);

}

在 fooV 调用中,创建了局部变量值 ...因此调用者中的数据不会被更新但是如果我想从 fooV 返回值怎么办?我应该向 fooV 添加什么?谢谢

最佳答案

你需要在 通过引用 中传递 v,这在 C 中使用指针完成:

void fooV(Value* v)
{
(*v).id = 10;
(*v).type = 'L';
(*v).a = 'R';
}

或者使用 -> 速记运算符:

void fooV(Value* v)
{
v->id = 10;
v->type = 'L';
v->a = 'R';
}

并且不要忘记传递 v 的地址:

fooV(&v);

关于c - 从结构返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1678312/

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