c - 按值传递和返回结构(带有数组成员)

标签 c arrays return structure pass-by-value

我知道在 C 中您可以按值传递(或返回)结构,但不能按值传递数组。当结构包含数组时会发生什么?当结构按值传递(或返回)时,数组(在结构内)是否会被复制?我跑了a sample at ideone.com它有效,但我想知道标准中的哪些地方涵盖了这一点(是的,我看过了)。

http://open-std.org/JTC1/SC22/WG14/www/docs/n1256.pdf

typedef struct
{
    float aValue;
    int anArray[5];
} myStruct;

myStruct addValueToArray(myStruct in)
{
    myStruct out = in;

    int i;
    for (i = 0; i < 5; i++)
    {
        out.anArray[i] = in.anArray[i] + in.aValue;
    }

    return out;
}

最佳答案

是的,它将被复制。整个结构是一个值,因此它可以传递给函数、返回和(很多人似乎忘记了这一点,但你会用到它,太好了!)赋值。

请注意,可能存在的任何填充都不需要复制,这使得 = 有可能比手动调用更快 memcpy() 可能是,因为它永远无法做到这一点。

很难在 PDF 中找到支持这一点的地方,但我在查找方面不是很有经验。基本上,struct 实例是 C 意义上的“值”,因此大部分讨论都自动涵盖了 struct

喜欢:

(6.2.5, part 1) The meaning of a value stored in an object or returned by a function is determined by the type of the expression used to access it.

(6.2.5, part 20) A structure type describes a sequentially allocated nonempty set of member objects (and, in certain circumstances, an incomplete array), each of which has an optionally specified name and possibly distinct type.

(6.8.6.4, part 3) If a return statement with an expression is executed, the value of the expression is returned to the caller as the value of the function call expression.

关于c - 按值传递和返回结构(带有数组成员),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13383224/

相关文章:

c - 跳过我的 while 语句,只为我的数组打印 63 个数字

function - 从 vbscript 中的函数返回二维数组

java - 为什么输出会有差异?

c++ - 在 Ubuntu Linux 中使用 Nvidia 卡的 OpenCL 出现 -1001 错误

c - eglSwapBuffers 在 Raspberry Pi 上非常慢

c - 如何将文件的行保存在字符串表中?

c# - 如何在不知道要存储多少值的情况下创建数组?

javascript - 数据错误() : "TypeError: Cannot read property ' length' of undefined"(Vue. js)

java - 需要帮助在线程运行方法中返回对象

java - 这个 boolean 方法有什么问题?