0

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.

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
Ricardo
  • 65
  • 5

1 Answers1

3

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.

dbush
  • 205,898
  • 23
  • 218
  • 273
  • Yes, that makes sense. You might want to point out that, since it's a global, you already get zero initialization of the arrays, just as `calloc` provides. (C99 6.7. 8.10) – Robert Harvey Oct 29 '21 at 16:10
  • @RobertHarvey Ah, I see, thanks, I was about to ask about that. However, is that initialization to the *bytes* of each variable, like `calloc` does, or does it set the *values* of the floats to zero? – Ricardo Oct 29 '21 at 16:14
  • @Ricardo: https://stackoverflow.com/a/28601320: *"Happily, zero is actually zero no matter what: IEEE-754 (the usual standard for floats) sets aside the all-zeroes bit pattern as meaning identically zero."* – Robert Harvey Oct 29 '21 at 16:16
  • @Ricardo According to the C standard the values are set to +0, however if your system uses IEEE754 floating point representation then the bytes are also 0. – dbush Oct 29 '21 at 16:16
  • I understand, thanks, this answers all my questions then. – Ricardo Oct 29 '21 at 16:18