arrays - 将数组分配给结构中的数组

标签 arrays c struct

我正在尝试将数组分配给 typedef 结构的其中一个字段,但我找不到切实可行的方法。

我已经搜索过这个问题,但我似乎只找到了 char * 数组的答案,这不是我要找的,我只是想将一个数组分配给一个 int 数组,并寻找一个以下代码无需初始化结构中的所有变量即可运行的实用方法(它们将在稍后初始化,但我只想设置数组变量):

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
}

请假设 config 稍后被调用,并且 struct 和 RA 都可以访问它。

最佳答案

RA.array = {1, 2, 3, 4, 5};

memcpy(RA.array, (int[]){1, 2, 3, 4, 5}, sizeof RA.array);

RA.array = arr;

memcpy(RA.array, arr, sizeof arr); // better: sizeof RA.array

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

相关文章:

c - Realloc() 在我的动态数组中引入随机值

javascript - 用另一个数组过滤 AngularJS 数组

c - 数学库中的文字常量与变量

C#define 语句、枚举、结构

struct - Go 结构和字节数组之间的转换

javascript - 在 Javascript 中按日期对数组数组进行排序

mysql - 我如何从 laravel 中的数组中获取值

c - 如何在此函数中返回2个结果

c - 如何在 CLion 中自动生成和更新 .h 文件的函数声明(原型(prototype))?

c++ - 在C++中初始化结构的成员变量