2011-09-27 95 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])。但是,首先分配內存。