在结构中初始化数组的值 [英] Initialize values of array in a struct

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

问题描述

我有一个结构体,其中包含多个数组.数组的类型为 unsigned char[4].

I have a struct which has several arrays within it. The arrays have type unsigned char[4].

我可以通过调用

struct->array1[0] = (unsigned char) something;
... 
struct->array1[3] = (unsigned char) something;

只是想知道是否有办法在一行中初始化所有 4 个值.

Just wondering if there is a way to initialize all 4 values in one line.

解决方案:我需要创建一个临时数组并初始化所有值,然后调用 memset() 将值复制到结构数组中.

SOLUTION: I needed to create a temporary array with all the values initialized, then call memset() to copy the values to the struct array.

推荐答案

如果值相同,你可以做类似的事情

If the values are the same, you might do something like

struct->array[0] = struct->array[1] = struct->array[2] = struct->array[3] = (unsigned char) something;

否则,如果值存储在数组中,则可以使用 memcpy 类似这样的功能

Otherwise, if the values are stored in an array, you can use the memcpy function like so

memcpy(struct->array, some_array, sizeof(struct->array));

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

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