MikhaelM
MikhaelM

Reputation: 173

Creating matrix issue

I'm having some trouble creating a user-input matrix through a function I create. The function is as follows:

int create(int l, int c, int one[MAX][MAX])
{
    for(int i = 0; i < l; ++i)
        for(int j = 0; j < c; ++j)
        scanf("%d", &one[i][j]);
}

I then proceed to call my function from main :

int main()
{
    int mat[MAX][MAX];
    int lines, collumns;
    printf("Input # of lines, columns:\n");
    scanf("%d %d", &lines, &collumns);

    create(lines, collumns, mat[MAX][MAX]);
}

Oddly, if I copy the function to main and just run it as so, it works fine. But it just won't work if I try doing so through function calling, as my program crashes. What am I doing wrong guys?

Upvotes: 0

Views: 55

Answers (2)

Lallu Anthoor
Lallu Anthoor

Reputation: 231

Well, when passing multidimensional arrays into a function in C, the basic rule is

You should specify the value for each of the dimension other than the first one.

So when you are passing a 2D array, define like this.

int create( int l, int c, int one[][MAX] ){...}

And when passing 3D array, define like this.

int create3D( int x, int y, int z, int mat[][MAX_Y][MAX_Z] ){...}

And when invoking the function, you only need to specify the name of the array variable. No need to specify the dimensions.

create( l, c, one );
create3D( x, y, z, mat );

You can see these errors/warnings if you compile with -Wall switch in gcc.

Good Luck!

Upvotes: 0

Lee Duhem
Lee Duhem

Reputation: 15121

Change

create(lines, collumns, mat[MAX][MAX]);

to

create(lines, collumns, mat);

and try again.

Upvotes: 2

Related Questions