2015-09-27 119 views
0

我學習C.我有如下所示方案動態矩陣分配

#include <stdio.h> 
#include <stdlib.h> 
#include <time.h> 

void main(){ 

int i, j, k, m, n; 
double **x; 
double **y; 
printf("Enter a number as the size of two square matrices\n"); 
scanf("%d", &m); 
x = (double**)malloc(m * sizeof(double)); 
y = (double**)malloc(m * sizeof(double)); 
/* initialize random seed: */ 
srand(time(NULL)); 
for(i = 0; i < m; i++) { 
    x[i] = (double*)malloc(m * sizeof(double)); 
    y[i] = (double*)malloc(m * sizeof(double)); 
    for(i = 0; i < m; i++) { 
     for(j = 0; j < m; j++) { 
      x[i][j] = rand(); 
      y[i][j] = rand(); 
     } 
     printf("\n"); 
    } 
    } 
    printf("\n\n"); 
} 

當運行此程序,動態創建並填充兩個矩陣X和Y,在使用RAND()隨機數的程序並給出2作爲我的矩陣大小,我看到「Segmetation Fault」錯誤。請注意,這個想法是用double類型的隨機元素填充這兩個矩陣。讓我知道如果上面的代碼是正確的。

更正:EDIT1

x = (double**)malloc(m * sizeof(double*)); 
y = (double**)malloc(m * sizeof(double*)); 
/* initialize random seed: */ 
srand(time(NULL)); 
for(i = 0; i < m; i++) { 
    x[i] = (double*)malloc(m * sizeof(double)); 
    y[i] = (double*)malloc(m * sizeof(double)); 

    for(j = 0; j < m; j++) { 
     x[i][j] = rand(); 
     y[i][j] = rand(); 
    } 
    printf("\n"); 

    } 
    printf("\n\n"); 
} 

以上,現在正常工作。需要關於 的一些解釋x =(double **)malloc(m * sizeof(double *)); 和 x [i] =(double *)malloc(m * sizeof(double)); (double *)malloc(m * sizeof(double *)); sizeof(double *)in x =(double **)

EDIT2

void main(){ 

int i, j, k, m, n; 
printf("Enter a number as the size of two square matrices\n"); 
scanf("%d", &m); 

double (*x)[m] = malloc(sizeof(double[m][m])); 
double (*y)[m] = malloc(sizeof(double[m][m])); 
/* initialize random seed: */ 
srand(time(NULL)); 
for(i = 0; i < m; i++) { 
    for(j = 0; j < m; j++) { 
     x[i][j] = rand(); 
     y[i][j] = rand(); 
    } 
    printf("\n"); 

    } 
    printf("\n\n"); 
} 

作爲每改變延Gustedt矩陣分配...我已刪除

double **x; 
double **y; 
x = (double**)malloc(m * sizeof(double*)); 
y = (double**)malloc(m * sizeof(double*)); 
x[i] = (double*)malloc(m * sizeof(double)); 
y[i] = (double*)malloc(m * sizeof(double)); 
+0

不,這是不正確的。獲得seg故障清楚地告訴您存在問題。建議您在調試器中運行程序和/或添加調試打印語句以嘗試查找您的問題。你也可以看看這個問題中的「相關」鏈接。這種矩陣分配已經有很多次了。 – kaylum

+0

user3121023感謝您指出。我添加了*並刪除了內部循環。 –

+0

@ user3121023你能解釋一下行嗎 x =(double **)malloc(m * sizeof(double));和x [i] =(double *)malloc(m * sizeof(double)); –

回答

0

這些僅僅是假的矩陣和該技術屬於成一個博物館。在現代C中,自C99以來,只需將一個2D矩陣分配爲double (*matrix)[m] = malloc(sizeof(double[m][m]));即可。因此,您只需要對整個矩陣調用malloc,並將其全部存儲在連續內存中。
- Jens Gustedt