开发者

Seg Fault while trying to fill in a matrix contained in a struct

I've got a structure for a matrix :

struct Matrice{

    int nblig;
    int nbcol;
    int **mat;

};

And my program's got a seg fault when i try to fi开发者_如何学Cll the matrix :

void initMat(Matrice *M)
{
    int j, i;
    srand(time(0));
    M->nbcol = (rand()%5)+1;
    M->nblig = (rand()%5)+1;
    for(i=0; i<M->nbcol;i++){
        for(j=0; j<M->nblig;j++){
           M->mat = rand()%101; //segfault here
        }
    }
}

It's been a while i've not practised C, anyone got a clue on why i've got this segfault?

Thanks.


I find it hard to believe that the program segfaults exactly at that line, but it's quite likely that it will segfault at some time if you assign a random value to a pointer.

You should allocate memory for the matrix using malloc; multiple times, in fact, if you use a double pointer structure. When handling matrices in C, I tend to use a different structure:

struct Matrix {
    size_t ncols, nrows;
    int *mat;
};

then initialize the mat member with malloc(ncols * nrows) and index with mat[i * nrows + j]. The indexing is a bit harder, but the memory management is a lot easier and some matrix operations likely become a lot faster because everything is stored in one array.


It looks like you're trying to assign a number to mat. There are two things that look wrong with this: - You need to allocate memory for mat. Right now you have a pointer there, but by default it doesn't point to anything. - You're assigning to mat directly, treating it like a single integer. If it's supposed to be a matrix, you probably want to index based off of it (like M->mat[i][j]). Allocate the memory first, though.


You need to initialize the mat member into a two-dimensional array of the appropriate number of rows and columns.

void initMat(Matrice *M)
{
    int j, i;
    srand(time(0));
    M->nbcol = (rand()%5)+1;
    M->nblig = (rand()%5)+1;

    M->mat = malloc(nbcol * sizeof(int));
    if (!M->mat)
    {
        /* memory allocation failed */
    }

    for(i=0; i<M->nbcol;i++){
        M->mat[i] = malloc(nblig * sizeof(int));
        if (!M->mat[i])
        {
            /* memory allocation failed */
        }

        for(j=0; j<M->nblig;j++){
           M->mat[i][j] = rand()%101;
        }
    }
}

You need to #include <stdlib.h> in order to have (warning-free) access to the malloc function.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜