I have a struct which has several arrays within it. The arrays have type unsigned char[4].
I can initialize each element by calling
struct->array1[0] = (unsigned char) something;
...
struct->array1[3] = (unsigned char) something;
Just wondering if there is a way to initialize all 4 values in one line.
SOLUTION: I needed to create a temporary array with all the values initialized, then call memset() to copy the values to the struct array.
struct->array1[0] = (unsigned char) something; ... struct->array1[3] = (unsigned char) something; Just wondering if there is a way to initialize all 4 values in one line. SOLUTION: I needed to create a temporary array with all the values initialized, then call memset() to copy the values to the struct array.
A structure may contain elements of different data types – int, char, float, double, etc. It may also contain an array as its member. Such an array is called an array within a structure. An array within a structure is a member of the structure and can be accessed just as we access other elements of the structure.
An initializer for a structure is a brace-enclosed comma-separated list of values, and for a union, a brace-enclosed single value. The initializer is preceded by an equal sign ( = ).
If you really mean "initialize" in the sense that you can do it at the time you declare the variable, then sure:
struct x {
unsigned char array1[4];
unsigned char array2[4];
};
struct x mystruct = {
{ 1, 2, 3, 4 },
{ 5, 6, 7, 8 }
};
When you create the struct, you can initialise it with aggregate initialisation:
struct test {
int blah;
char arr[4];
};
struct test = { 5, { 'a', 'b', 'c', 'd' } };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With