Initialize integer variable on typedef in C

salimsaid Source

I have a definition for int with my preferred name like so

Step 0 :

define array type of 128 elements

typedef int ishida_opcua_array[128];

and later i have a function to initialize the type ishida_opcua_array

void ishida_opcua_array_init(ishida_opcua_array array)

        int i;
        for(i = 0; i < 128; i++)
            array[i] = -56565;


And finally; this is how i use the ishida_opcua_array type

Step 1 :

define an array of type ishida_opcua_array

 ishida_opcua_array source_array;

Step 2 :

Initialize source_array with ishida_opcua_array_init() function

  * Then i can do whatever i want with [source_array]

How can i declare and initialize the array with the typedef, i want to be able to do

 * Define the variable and you are ready to go
 * initialization has already been done while creating the variable
ishida_opcua_array already_initialized_array;  //already initialzed, ready to use

Please note in the first step, i had to first define the variable like so

ishida_opcua_array source_array;

then initialize the variable using below function



answered 6 months ago Aconcagua #1

ishida_opcua_array already_initialized_array = { 1, 2, 3 };

Of course, this would only initialise the first three members specifically and the rest to 0; you could use macros to generate your initialiser:

#define INIT_0 -56565          // well, prefer a better name...
#define INIT_1 INIT_0, INIT_0
#define INIT_2 INIT_1, INIT_1

up to INIT_7 and then have

ishida_opcua_array already_initialized_array = { INIT_7 };

Not going to judge if this really is better than your function...

comments powered by Disqus