gpt4 book ai didi

c - 将存储分配给矩阵

转载 作者:太空狗 更新时间:2023-10-29 16:04:06 27 4
gpt4 key购买 nike

我正在编写一个将存储分配给 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;

这是为什么?

最佳答案

您已经(完美地)为您的矩阵分配了内存,但您实际上并没有将它分配给来自被调用方的 A 变量。相反,A 最终仍未初始化,并且尝试分配给 A[1][1] 导致了段错误。为此,您需要一个指向该变量的指针并将矩阵分配给该地址。所以实际上,您的函数签名和实现需要更改:

/* take a pointer to a (double **) */
void assign_matrix_storage(double ***matrix, int n){
/* then all accesses need to dereference first */
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;
}

/* then call */
double **A;
assign_matrix_storage(&A, 2);
A[1][1] = 42;

一个更好的替代方法是将指针返回到新矩阵并将其分配给您的变量。

double **assign_matrix_storage(int n) {
double **matrix;
/* the rest of your implementation */
return matrix;
}

double **A;
A = assign_matrix_storage(2);
A[1][1] = 42;

关于c - 将存储分配给矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5775000/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com