Home > other >  Using extern with multidimentional arrays in C
Using extern with multidimentional arrays in C

Time:10-30

I have a bunch of multidimensional arrays that are allocated in local functions in different source files, but I want to make them global. I was thinking of using extern and according to this question, I need to make a header file that includes the declaration of my variable and then define that variable, only once, within one of the source files.

However, the method I'm using to generate multidimensional arrays both declares and defines the variable in one line, like so:

float (*data0)[224][3] = calloc(224, sizeof *data0);

Is there a way I can split this into declaration and definition so that I can use this method, or would it be better to just do both at the header file itself?


I am making a neural network implementation in C and I have a lot of those arrays defined in multiple places. At first I didn't think I would need them at a later point, and this is supposed to run in an embedded system with memory constraints, so I made these arrays all local and used free on them as soon as possible.

But it turns out I will need them for the training of this network so I need them to be global so that they save their values over many iterations of the functions. Plus, I didn't know that the system we will use will have a 64MB DRAM attached to it, so memory constraints are not as much of a problem.

CodePudding user response:

If you're defining these arrays globally, there's no need to dynamically allocate memory. Unlike stack space, there's no practical limit to how big globals can be.

So assuming you want a 3D array with dimensions 224, 224, and 3, define it as follows:

float data0[224][224][3];

Then declare it in your header file as:

extern float data0[224][224][3];

Also, globals are zero-initialized by default, so no need for an explicit initializer.

  • Related