Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize values of array in a struct

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.

like image 660
Nick Schudlo Avatar asked Mar 24 '12 22:03

Nick Schudlo


People also ask

How do I initialize an array in a struct?

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.

Can you place an array inside a structure?

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.

How do you initialize a struct value?

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 ( = ).


2 Answers

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 }
};
like image 118
Carl Norum Avatar answered Sep 23 '22 19:09

Carl Norum


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' } };
like image 38
Seth Carnegie Avatar answered Sep 25 '22 19:09

Seth Carnegie