动态矩阵分配程序

时间:2015-09-27 22:58:54

标签: c matrix

我正在学习C.我有一个动态创建和填充两个矩阵X和Y的程序,使用rand()随机数,如下所示

#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");
}

当我运行这个程序并给出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));

为什么* for sizeof(double *)in x =(double **)malloc(m * sizeof(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");
}

根据Jens 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));

1 个答案:

答案 0 :(得分:0)

这些只是伪造的矩阵,这种技术属于博物馆。在现代C中,从C99开始,只需将二维矩阵分配为CREATE TABLE users ( userId INT PRIMARY KEY AUTO_INCREMENT NOT NUll, account VARCHAR(200) NOT NULL, password varchar(200) NOT Null, isActive varchar(10) NOT NUll, createdDate DATETIME DEFAULT CURRENT_TIMESTAMP NOT NUll, updatedDate DATETIME ); 。因此,您只需要对整个矩阵调用onTouch,并将其全部放在连续的内存中 - Jens Gustedt