-3

I am learning c language and always confused with the array return using pointers.My question is:

I want to read and declare the 2D array inside

int ** readMatrix(int rows,int cols); function

and return it to the main()

plz give me the solution in simple language because I was already go through many books but couldn't understand. thank you

5
  • Nice profile picture though :P
    – babon
    Jul 17, 2017 at 13:34
  • int** is not 2D array. Also, show what have you tried so far. "give me the solution" will not get you much here... Jul 17, 2017 at 13:34
  • 1
    Please, look on malloc function and read something about memory allocations in C language. Jul 17, 2017 at 13:34
  • The reason you haven't found an explanation in simple language is that constructing and returning 2D arrays in C is hard. My suggestion is that in the caller you say int matrix[NROWS][NCOLS]; and then rewrite readMatrix so that you can call readMatrix(matrix, NROWS, NCOLS). In other words, allocate the matrix in the caller, and have the called function just fill in that matrix. Jul 17, 2017 at 13:58
  • @SteveSummit thanks for your suggestion but I did this already. Jul 17, 2017 at 18:26

1 Answer 1

0

To initialize memory for an 2D array within in another function with the intent to use the very same memory outside this function you must use malloc to ask for the required memory from the OS.

Malloc returns an void pointer to the start adress of the block of memory you requested or NULL if the request could not be served from the OS, which nowadays with home PC's is very unlikely to happen because it means you have run out of memory. malloc doc

If you want to create array of pointer of type Int you have to do the following

see

int ** readMatrix(int rows,int cols){
     int** var = (int**) malloc(sizeof(int)*rows); //Here you allocate the memory for the pointer which will later point the the columns
     for (int i=0; i<r; i++)
        arr[i] = (int *)malloc(cols * sizeof(int)); //Here you allocate the columns

      return var; 
 }

another way would be to map an 2D array onto an 1D array. What do I mean with mapping? Let me show it with an example:

If you want to map all Elements from an 2D array onto 1D array the 1D array must have the same number of Elements as the 2D array otherwise you would miss elements. Then you need some kind of formula to calc the index from 2D array to an 1D array. The formula is: y*width+x

Width represent the maximum amount of elements one row of the 2D array can contain. X represent your position on the current row and Y represent the row you are currently at.

in C it would look like this:

 int* var = malloc(sizeof(int)*rows*cols);
 for(int i = 0; i < row; i++)
    for(int j = 0; j < cols; j++)
       var[i*cols+j] = 0;

Not the answer you're looking for? Browse other questions tagged or ask your own question.