问题描述
我正在尝试将一个数组分配给 typedef 结构的一个字段,但我找不到实际的方法.
我已经搜索过这个问题,但我似乎找到的只是 char * 数组的答案,这不是我要找的,我只是想将一个数组分配给一个 int 数组,并寻找一个以下代码无需初始化结构中的所有变量即可工作的实用方法(稍后将对其进行初始化,但我只想设置数组变量):
typedef struct {整数数组[5];整数;腐烂;腐烂 RA;无效的配置(){RA.array = {1, 2, 3, 4, 5};//这将返回{"错误之前的预期表达式"int arr[5];国际我;for (i = 0; i
请假设稍后会调用 config,并且 struct 和 RA 都可以访问它.
解决方案
memcpy(RA.array, (int[]){1, 2, 3, 4, 5}, sizeof RA.array);
RA.array = arr;
memcpy(RA.array, arr, sizeof arr);//更好:sizeof RA.array
I'm trying to assign an array to one of the fields of a typedef struct and I can't find a way to do it practically.
I've searched for this problem but all I seem to find is answers for char * arrays which is not what I'm looking for, I'm just trying to assign an array to an int array, and looking for a practical way for the code below to work without having to initialize all the variables in the struct (they will be initialized later, but I just want to set the array variable):
typedef struct {
int array[5];
int number;
} Rot;
Rot RA;
void config()
{
RA.array = {1, 2, 3, 4, 5}; //This returns an "expected expression before "{"" error
int arr[5];
int i;
for (i = 0; i < 5; i++)
{
arr[i] = i + 1;
}
RA.array = arr; //I understand why this fails, but I need to do this in a practical way
}
Please assume that config is called later and the struct and RA are all accessible to it.
解决方案
memcpy(RA.array, (int[]){1, 2, 3, 4, 5}, sizeof RA.array);
memcpy(RA.array, arr, sizeof arr); // better: sizeof RA.array
这篇关于将数组分配给结构中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!