Returning Two Dimensional Array from a Function in C

Many authors do not include topics about returning an array from a function in their books or articles. It is because, in most of the cases, there is no need of array to be returned from a function. Since, on passing the array by its name, the address of its first member is passed and any changes made on its formal arguments reflects on actual arguments.


But sometimes, there may arise the situation, where an array has to be returned from a function, for example, multiplying two matrices and assigning the result to another matrix. This can be done by creating a two-dimensional array inside a function, allocating a memory and returning that array. The important thing is you need to FREE the matrix that was allocated.

The source code of returning a two-dimensional array with reference to matrix addition is given here.


Or you can use a structure that has a two-dimensional array as a member. Create an instance of structure inside the function and return it.  The code for this approach is given below.


SHARE Returning Two Dimensional Array from a Function in C

You may also like...

9 Responses

  1. vad says:

    excellent, very insightful.

  2. Awesome Code, Helped a lot, take away a lot of headache. Thanks

  3. sanjana says:

    thank u…it helped me a lot…

  4. Anonymous says:

    thx brother.

  5. Sorry but you are just modifying the contents of matrix1 in the function using its base address and returning it back to main.
    What is something expected is to create an array inside the called function and return it to the calling function(i.e main in this case).
    is there any simple way out for doing so?

  6. The code is corrected to make it more reasonable. Thank you!!

  7. shyam says:

    sir can you show the same without using dynamic memory allocation?i mean fix some rows and columns for the formal parameters

Leave a Reply

Your email address will not be published. Required fields are marked *