I am trying to allocate a 2d contiguous array using C99 variable length arrays. Something like this:
size_t rows = 5, cols = 5;
double (*array)[cols] = malloc(rows * sizeof *array);
The trouble is, I want to do the allocation in a function. I'm guessing that in order to do so, I need to declare the array first and then pass its address to the function. I've been trying things like this:
#include <stdlib.h>
#include <stdio.h>
void allocate(double *((*grid)[]), size_t cols)
{
size_t rows = 5; // in practice this the result of a computation
double (*array)[cols] = malloc(rows * sizeof *array);
*grid = array;
}
int main ()
{
size_t cols = 5;
double (*grid)[cols]; // note: edited to fix typo (was [])
allocate(&grid, cols);
return 0;
}
My compiler (GCC 4.7.1) is giving me the following warnings/errors:
$ gcc -Wall -pedantic -std=c99 2d.c -o 2d
2d.c: In function ‘allocate’:
2d.c:8:5: error: invalid use of array with unspecified bounds
2d.c: In function ‘main’:
2d.c:16:5: warning: passing argument 1 of ‘allocate’ from incompatible pointer type [enabled by default]
2d.c:4:6: note: expected ‘double * (*)[]’ but argument is of type ‘double (**)[]’
I have tried many variations of this kind of thing but I am clearly missing something. I would like to have a contiguous 2d array accessible like grid[j][i] from main but perform the allocation in a separate function. How can I do this?
void allocate(double (**grid)[], size_t cols)return array;, and in main simplygrid = allocate(...);. Ah: The return type would best be done with a typedef (@user3477950).