【发布时间】:2011-08-12 02:41:48
【问题描述】:
我正在编写一个将存储分配给 nxn 矩阵的函数。
void assign_matrix_storage(double **matrix, int n){
if((matrix = malloc(n * sizeof(double*))) == NULL){
printf("ERROR: Memory allocation failed\n");
exit(EXIT_FAILURE);
}
int i;
for(i = 0; i < n; i++){
if((matrix[i] = malloc(n * sizeof(double))) == NULL){
printf("ERROR: Memory allocation failed\n");
exit(EXIT_FAILURE);
}
}
return;
}
但是,如果我运行以下代码,我会在最后一条语句上得到一个段错误:
double **A;
assign_matrix_storage(A, 2);
A[1][1] = 42;
这是为什么?
【问题讨论】:
-
stackoverflow.com/questions/16004668/… 在上面你会发现一个程序,我用任何可能的方式为 C (gcc C11/C99) 分配和操作矩阵的函数。也许对你有用……
标签: c