2011-09-27 93 views
0

我有一个矩阵的结构:赛格故障而试图填补包含在结构矩阵

struct Matrice{ 

    int nblig; 
    int nbcol; 
    int **mat; 

}; 

而我的程序得到了赛格故障,当我尝试填补矩阵:

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 
     } 
    } 
} 

我已经有一段时间没练习C了,任何人都知道为什么我有这段错误?

谢谢。

+2

你永远不会分配你的矩阵。 (至少不在你显示的代码中)。 –

回答

1

您需要将mat成员初始化为具有适当行数和列数的二维数组。

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; 
     } 
    } 
} 

您需要#include <stdlib.h>为了有(无警告)访问malloc功能。

+0

这是'',你应该检查错误返回。 –

+0

呃。最近.NET太多了。固定。 –

+0

我以为我发现了C++程序员混淆了''和''的习惯:) –

3

我觉得很难相信该程序的段错误正好在那一行,但如果给一个指针指定一个随机值,它很可能会在某个时间段发生段错误。

您应该使用malloc为矩阵分配内存;事实上,如果您使用双指针结构,则会多次。当用C处理的矩阵,我倾向于使用不同的结构:

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

然后用malloc(ncols * nrows)和索引与mat[i * nrows + j]初始化mat构件。索引有点难度,但内存管理要容易得多,而且一些矩阵操作可能变得更快,因为everything is stored in one array

1

它看起来像你试图分配一个数字垫。有两件事看起来是错误的: - 您需要为垫子分配内存。现在你有一个指针,但默认情况下它不指向任何东西。 - 您直接分配给mat,将其视为单个整数。如果它应该是一个矩阵,那么可能需要基于它进行索引(如M-> mat [i] [j])。但是,首先分配内存。