# What would the prototype declaration of a C function look like that returns an n-dimensional array?

<>This question already has an answer here:

## Answers

I would suggest this:

array foo();

where array is an struct defined as:

struct array { int *data; unsigned int ndim; //number of dimensions unsigned int *size; //size of each dimension is size[i]. };

Of course, data is just a pointer to int, but the other two fields in the struct can be used in such a way that the data can be interpreted like an n dimensional array, and size of each dimension can be stored in size which is yet another pointer.

For example, take 4-dimensional array (dimension size are 10, 20, 30 and 40), then you can create and initialize *4D array* as:

unsigned int size[] = {10,20,30,40}; array arr = create(4, size);

where create function is defined as:

array create(unsigned int n, unsigned int *size) { array arr; arr.ndim = n; arr.size = (unsigned int*) malloc(n * sizeof(unsigned int)); int i; unsigned int totalElements = 1; for( i = 0 ; i < n ; ++i) { arr.size[i] = size[i]; totalElements *= size[i]; } arr.data = (unsigned int*) malloc(totalElements * sizeof(int)); return arr; }

Of course, you've to work a lot with the fields of the struct, to make it look like n-dimensional array. You don't need to follow me exactly the way I explained, but this is just a basic idea. You can modify it, to suit your specific need.

I would suggest you to write few functions, to manipulate the array, and to access the array elements. I've written create function, likewise here is destroy function:

void destroy(array arr) { if (arr.size != NULL && arr.data != NULL) { free(arr.size); free(arr.data); arr.size = arr.data = NULL; } }