What is the wrong with below code?

I have tried to pass 2d array to function but it shows error. please help me to resolve this code. I have little bit idea about 2d array.


[1] 


  [1]: http://ideone.com/dLkB42

Actually, I am not good with pointers, but you can pass 2d array to a function like this ->>

#include <stdio.h>
const int M = 3;
const int N = 3;
 
void print(int arr[M][N])
{
    int i, j;
    for (i = 0; i < M; i++)
      for (j = 0; j < N; j++)
        printf("%d ", arr[i][j]);
}
 
int main()
{
    int arr[][N] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    print(arr);
    return 0;
}

source: http://www.geeksforgeeks.org/pass-2d-array-parameter-c/

int** arr = new int*[row] ==> you declared arr as a 1-dimensional array.

There are many things wrong.

Firstly, even for 1-D array, such type of declarations are wrong-

int arr[5];
arr[5]={1,2,3,4,5};

If above is wrong, then so is your 2-D declaration of array, The error gotten is same, which is -cannot convert ‘<brace-enclosed initializer list>’ to ‘int’ in assignment arr[row][colum] = {{1, 2, 3}, {4, 5, 6}};

Either you initialize it using loops, or you initialise it in the same statement of declaration. Eg- int arr[2][3]={{1,2,3},{1,2,3}};

If after correcting this you get the error, then refer-

1 Like

If you want to stick your way of doing it, then you can do it like this

Instead of this

arr[row][colum] = {{1, 2, 3}, {4, 5, 6}};

Write the following lines

int a[3] = {1,2,3}, b[3] ={4,5,6};
arr[0] = a;
arr[1] = b;

This will point row[ 0 ] of arr to array a and row 1 of arr to array b.

You code works fine after the above changes. http://ideone.com/vhZpCz

The problem is that you cannot use a “brace-enclosed initializer list” to initialize an array only while declaration.

int** arr = new int* [row]

He declared arr as a pointer to an array of pointers each of which later points to a unique row. I think its right.

1 Like

@vijju123 has the point.After correcting the array initialization, it’s working fine.
Here is the link:https://pastebin.com/i1VueMwh

Please tell me - how to solve it?