Hi guys.
I'm writing a function for my program.
This function is required to return an array or at least a pointer to an array.
The array is 2 dimensional.
How do i do this in the function, and how do i call the function in the mainline?
Hi guys.
I'm writing a function for my program.
This function is required to return an array or at least a pointer to an array.
The array is 2 dimensional.
How do i do this in the function, and how do i call the function in the mainline?
Perhaps you could try this:
... and calling this in main function will look likeCode:int** foo(int x, int y) { int** arr = malloc ( x * sizeof( *arr ) ); // allocate memory for rows int i; for ( i = 0; i < x; i++ ) // for every row allocate y cells arr[i] = malloc ( y * sizeof( *arr[i] ) ); return arr; }
...which creates 5x5 matrix. Don't forget to free memory once you're done with it.Code:int** myArray = foo(5, 5);
You don't. You write the function to take a 2D stack array or 2D dynamic array. You modify the array through the argument.
The two prototypes look like this.
In each case accessing the array is done using brackets, like this: array [1][4].Code://ROWS should be a constant int takeStaticArray(int cols,int array[][ROWS] ); int takeDynamicArray(int cols, int rows, int **array);
The later is preferred, but the former is uses if you declare a 2d array in a function (as opposed to using malloc() or calloc() ).
Don't do what jimzy said, because it's bad style; any call to malloc() should be matched by a call to free() in the same function. It will work if you call free() later outside the function, but its easy to mess up, so it should be avoided whenever possible.
It is too clear and so it is hard to see.
A dunce once searched for fire with a lighted lantern.
Had he known what fire was,
He could have cooked his rice much sooner.
Why should we use free()? what is it that we have to free?