I want to write a function in C language which returns the 2 dimension array to my main function.
4 Answers
A function that returns a dynamically allocated two dimensional array for the int type.
int ** myfunc(size_t width, size_t height)
{
return malloc(width * height * sizeof(int));
}
It has to be deleted with free once it is not used anymore.
EDIT This only allocates the space for the array which could be accessed by pointer arithmetic but unfortunately not by the index operators like array[x][y].
If you want something like this here is a good explanation. It boils down to something like this:
int ** myfunc(size_t ncolumns, size_t nrows)
{
int **array;
array = malloc(nrows * sizeof(int *));
for(i = 0; i < nrows; i++)
{
array[i] = malloc(ncolumns * sizeof(int));
}
}
4 Comments
int ** if you allocated like this. int ** is an array of pointers. If you do int **p=myfunc(xsize,ysize), and try to access p[x][y], you will crash.array[x][y] would crash the program. I'll update my answer.int ** which is essentially the same thing.You can not simply return malloc( x * y * sizeof(type) );
This will produce a segmentation fault when you try to index the array as a 2 dimensional array.
int **a = malloc(10 * 10 * sizeof(int));
a[1][0] = 123;
a[0][1] = 321;
The result of the above: Segmentation fault
You need to first create an array of pointers with c/malloc() then iterate this array of pointers and allocate space for the width for each of them.
void *calloc2d(size_t x, size_t y, size_t elem_size) {
void **p = calloc(y, sizeof(void*));
if(!p) return NULL;
for(int i = 0; i < y; i++) {
p[i] = calloc(x, elem_size);
if(!p[i]) {
free2d(y, p);
return NULL;
}
}
return (void*)p;
}
And free
void free2d(size_t y, void *matrix) {
if(!matrix) return;
void **m = matrix;
for(int i = 0; i < y; i++) {
if(m[i]) free(m[i]);
}
free(m);
return;
}
4 Comments
int **, but you don't have to use an array of pointers to get a 2D matrix.int (*matrix)[width] = malloc( width * height * sizeof(int));width information with a naked pointer.If you know the size of the array, you can do so:
int (*myfunc())[10] {
int (*ret)[10]=malloc(10*10*sizeof(int));
return ret;
}
This function return pointer to 10 arrays of 10 ints.
Of course, you should use it as it is, and don't forget to free it after using.