C 用于返回结构的函数名

C 用于返回结构的函数名,c,struct,C,Struct,我想创建一个函数,在其中我更改了一个已经存在的结构。因此,该函数的返回值应该是一个结构。如果我想要一个int作为返回值,我调用函数“int example()”。。。如果要返回结构,如何调用该函数?由于“struct”已被采用-我已采用“struct which”来创建一个结构。如果希望函数修改现有结构,则应通过指针将结构传入: void modify_thing(struct whatever *thing); 如果要返回结构的修改副本,可以按值返回结构: struct whatever e

我想创建一个函数,在其中我更改了一个已经存在的结构。因此,该函数的返回值应该是一个结构。如果我想要一个
int
作为返回值,我调用函数“
int example()
”。。。如果要返回结构,如何调用该函数?由于“struct”已被采用-我已采用“
struct which
”来创建一个结构。

如果希望函数修改现有结构,则应通过指针将结构传入:

void modify_thing(struct whatever *thing);
如果要返回结构的修改副本,可以按值返回结构:

struct whatever edit_thing(const struct whatever *input);

请注意,按指针传递结构变量通常比按值传递更有效。

按值传递结构将导致编译器在内存中建立一个或多个只能用于该函数的保留区域

编译器通过插入对memcpy()的调用来操纵这些内存区域


最好是将指针传递到结构,然后返回结构更新操作成功/失败的简单指示。

如果要返回的结构类型是
struct which
,请编写
struct which示例(void)
作为函数原型(或
struct which example(struct which arg);
struct which example(struct which*argp)
)。使用已经存在的结构名称——您需要使用该名称才能在现有结构变量上分配结果传递给函数
testFoo(foo)
并返回为
return foo
,所以总结一下,我得到了一个名为“struct coordinates”的结构。然后,如果我想改变它的值(比如说用某物乘以每个坐标),我可以创建一个名为“struct coordinates ScalarMultiplication()”的函数,在该函数中写“coordinates.x*=a”?参见@nneonneo的答案。如果您传递一个指向函数的指针,您可以使用
coordinates->x*=a这样的代码修改结构中的项如果传递结构并返回修改后的结构,那么复制struct.Sorta的未修改项将浪费大量时间。如果要传入值并修改它,则需要将其作为指针传递,并且不需要函数返回新值:
void ScalarMultiplication(struct coordinates*c,int a){c->x*=a;c->y*=a;}
将执行此任务(并调用:
struct coordinates c0={2,3};ScalarMultiplication(&c0,4);)。或者您可以使用
struct coordinates ScalarMultiplication(struct coordinates c,int a){c.x*=a;c.y*=a;返回c;}`并将其称为
c0=ScalarMultiplication(c0,4)具有相同的结果。感谢您的回答!在本例中,我有一个(学习)任务,在edit_thing函数中返回修改过的结构。举个恰当的例子:“结构坐标ScalarMultiplication(float*multiplication)是正确的吗?@Yíu:你说你在修改一个现有的结构,所以
struct坐标ScalarMultiplication(const-struct-coordinates*coords,float*multiplier)
更合适。啊,当然,我还需要检索现有坐标。你能进一步解释一下“const”是什么意思吗?不会是“struct coordinates*coords”“够了吗?如果您返回一个修改过的副本,您不会希望意外地修改传入的结构。”
const
告诉编译器不应该更改输入。啊,明白了。非常感谢,先生!