Howdy folks,

Does anyone know if GCC is capable of creating a fixed length 1D array of an N-Dimensional array for reasons of speed? I've heard it matters quite a lot if one works constantly with N-Dimensional (with N != 1) compared to 1D arrays in terms of speed, but the changing an N-D array to an 1D array is quite easy code-wise, so I thought maybe the compiler would do it automagicly?

Thanks in advance,

Recommended Answers

All 2 Replies

All C compilers create all arrays as 1D arrays: the C language defines a strict mapping of multi-dimentional array to contiguous 1D array...

The standards specify that elements of declared arrays are contiguous. N-dimensional arrays are actually arrays of (N-1)-dimensional arrays. So ..... the compiler is required to do what you want (at least, in terms of storage).

In terms of mechanism of element access (eg accessing element_in_N_dimensions vs equivalent access of element_in_one_dimension) that's up to the compiler. But the math is pretty trivial so most self-respecting compiler writers will pick an efficient (hopefully optimal) approach.

There are some ways to force the compiler to do it particular ways (optimal or sub-optimal). For example;

int i, j;
   int ***array = malloc(sizeof(int **)*1000);

   for (i =0; i < 1000;++i)
   {
         array[i] = malloc(sizeof(int *)*1000);
         for (j =1000; j >= 0;--j)
         {
              array[i][j] = malloc(sizeof(int)*1000);
         }
   }

emulates a 3D array using a pointer-to-pointer-to-pointer. It also allocates elements of that pseudo-array in a manner that elements are unlikely to be contiguous. Since this happens at run-time, the compiler cannot behave as if the "array" is actually a contiguous one-dimensional array - because it might not be.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.