gpt4 book ai didi

c - 在c中分配给struct中的数组

转载 作者:太空狗 更新时间:2023-10-29 17:00:55 26 4
gpt4 key购买 nike

我有以下代码:

typedef struct Test {
long mem[1000];
} Test;

extern Test *test;
int main() {
Test *test = (Test *)malloc(sizeof(Test));
test->mem[0] = 1;
test->mem[1] = 2;
test->mem[2] = 3;
test->mem[3] = 4;
test->mem[4] = 5;
test->mem[5] = 6;
return 0;
}

它工作正常,但我想改变内存数组的初始化方式:

test->mem = {1,2,3,4,5,6};

但是 gcc 给我这个错误:

error: expected expression before '{' token test->mem = {1,2,3,4,5,6}; With arrow pointing to the left open braces.

它可以是什么?

谢谢!

编辑:我也试试这段代码:

long mem[1000] = {1,2,3,4,5,6};
test->mem = mem;

我从 gcc 得到这个错误:

error: incompatible types when assigning to type 'long int[1048576]' from type 'long int *' test->mem = mem;

我不允许使用任何 C 函数。

最佳答案

语法 something = { initial values } 只允许在 initializations 中定义对象,例如:

long mem[1000] = { 1, 2, 3, 4, 5, 6 };

x = value 等表达式是一个赋值,不能使用语法进行初始化。

一种替代方法是创建一个您初始化的临时对象,然后将该临时对象的内容复制到目标中:

static const long temporary[] = { 1, 2, 3, 4, 5, 6 };
memcpy(test->mem, temporary, sizeof temporary);

关于编辑:

数组不能赋值;如果 x 是数组,则 x = value 无效。但是,可以分配结构,因此另一种方法是创建一个结构作为临时对象,对其进行初始化并分配:

// (After the malloc is successful.)
static const Test temporary = { { 1, 2, 3, 4, 5, 6 } };
*test = temporary;

但是请注意,这段代码做了一些之前的代码没有做的事情。我之前展示的示例仅将六个元素复制到数组中。此代码创建类型为 Test 的临时对象,其中包含 1000 个元素,其中大部分为零,并将所有这些元素复制到 *test 中。即使编译器对此进行了优化并使用一些代码来清除 *test 而不是实际复制存储在内存中的零,这比仅复制六个元素花费的时间更长。因此,如果您只想初始化几个元素而不关心其余部分,请使用前面的代码。如果你想初始化所有元素(大部分为零),你可以使用后面的代码。 (即便如此,我还是会考虑替代方案,比如使用 calloc 而不是 malloc。)

关于c - 在c中分配给struct中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21293491/

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