absentcrysis
absentcrysis

Reputation: 55

Segmentation fault in Matrix - C

Segmentation fault occurs while running this code. I could not find anything abnormal and it runs if i change **mat to mat[3][3]. please tell what is wrong, thanks

#include<stdio.h>
void getdata(int **mat)
{
    int i,j;
    for (i=0;i<3;i++)
    {
        for (j=0;j<3;j++)
            mat[i][j] = rand()%3;
    }
}
void putdata(int **mat)
{
    int i,j;
    for (i=0;i<3;i++)
    {
        for (j=0;j<3;j++)
            printf("%d",mat[i][j]);
        printf("\n");
    }
}
void main()
{
    int mat1[3][3];
    int mat2[3][3];
    getdata(mat1);
    getdata(mat2);
    putdata(mat1);
}

Upvotes: 3

Views: 202

Answers (3)

David C. Rankin
David C. Rankin

Reputation: 84521

In addition to the other methods, if you know the dimensions of the matrix you will be passing to your function, then the only dimension required in the definition is the number of columns. You do not specify the number of rows. Your code can be rewritten simply as follows:

#include <stdio.h>
#include <stdlib.h>
void getdata(int mat[][3])
{
    int i,j;
    for (i=0;i<3;i++)
    {
        for (j=0;j<3;j++)
            mat[i][j] = rand()%3;
    }
}
void putdata(int mat[][3])
{
    int i,j;
    for (i=0;i<3;i++)
    {
        for (j=0;j<3;j++)
            printf("%d",mat[i][j]);
        printf("\n");
    }
}
int main(void)
{
    int mat1[3][3];
    int mat2[3][3];
    getdata(mat1);
    getdata(mat2);
    putdata(mat1);
    return 0;
}

output:

$ ./msf
110
121
100

Upvotes: 0

jxh
jxh

Reputation: 70372

Within main, mat1 and mat2 will decay to a pointer to int[3], which is not the same as int **. So, getdata() and putdata() will be treating the pointer value as a different type than it actually is, leading to undefined behavior.

int mat1[3][3];
int (*decayed_mat1)[3] = mat1;
assert(decayed_mat1 == &mat1[0]);

Arrays are passed by "reference" in C functions. What this really means is that the function parameter that is declared as an array type actually takes on the decayed type.

void getdata(int mat[3][3]);
void (*funcptr)(int (*)[3]) = getdata;

Changing your function parameter types to int[3][3] gives the parameter the type that matches what is being passed in.

Upvotes: 6

ashishk
ashishk

Reputation: 299

You have to use **mat while declaring the matrix because while you are passing the argument mat1[][] have already been allocated the memory but **mat which is local to function does not have the similar memory as mem1 so both the variable must have similar memory so either change in declaration part or while passing the argument. Thanks

Upvotes: -1

Related Questions