将数组分配给结构中的数组 [英] Assign an array to array in struct

查看:45
本文介绍了将数组分配给结构中的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一个数组分配给 typedef 结构的一个字段,但我找不到实际的方法.

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

typedef struct {整数数组[5];整数;腐烂;腐烂 RA;无效的配置(){RA.array = {1, 2, 3, 4, 5};//这将返回{"错误之前的预期表达式"int arr[5];国际我;for (i = 0; i <5; i++){arr[i] = i + 1;}RA.array = arr;//我明白为什么会失败,但我需要以实际的方式做到这一点}

请假设稍后会调用 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);//更好: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.

解决方案

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

这篇关于将数组分配给结构中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆