当函数修改动态分配的二维数组C.分段错误 [英] C. Segmentation Fault when function modifies dynamically allocated 2d array
问题描述
我需要的是改变给指针二维矩阵这样的功能:
What i need is a function that modifies given pointer to 2d matrix like this:
void intMatrixAll(int row, int col, int **matrix);
现在,一功能应该分配存储器,并且可以使用的基体。行列数在运行时中给出。
Now, a function should allocate memory and the matrix could be used. Rows and cols are given at run-time.
#include <stdio.h>
#include <stdlib.h>
#define PRINTINT(X) printf("%d\n", X);
void intMatrixAll(int row, int col, int **matrix);
int main(void) {
int testArrRow = 4;
int testArrCol = 6;
int **testMatrix = NULL;
intMatrixAll(testArrRow, testArrCol, testMatrix);
testMatrix[2][2] = 112; //sementation fault here :(
PRINTINT(testMatrix[2][2]);
system("PAUSE");
return 0;
}
void intMatrixAll(int row, int col, int **matrix) {
printf("intMatrixAll\n");
//allocate pointers:
matrix = malloc(row * sizeof(int *));
if(matrix == NULL) printf("Failed to allocate memmory.\n");
for(int i=0; i<row; i++) {
//allocate space for cols:
matrix[i] = malloc(col * sizeof(int));
if(matrix[i] == NULL) {
printf("Failed to allocate memmory for arr[%d].\n", i);
exit(0);
}
}
}
为什么会出现错误?
Why am i getting error?
推荐答案
由于修改里面intMatrixAll基质()不修改testMatrix在main()。如果您希望能够修改主要的变量,你需要一个指针传递给它。所以,你需要intMatrixAll更改为:
Because modifying matrix inside intMatrixAll() does not modify testMatrix in main(). If you want to be able to modify main's variable, you need to pass a pointer to it. So you need to change intMatrixAll to:
void intMatrixAll(int row, int col, int ***matrix)
里面intMatrixAll,你现在需要矩阵
更改为 *矩阵
(以及当你索引它,你会想要(*矩阵)[...]
。
Inside intMatrixAll, you'll now need to change matrix
to *matrix
(and for when you are indexing it, you'll want (*matrix)[...]
.
最后,你需要向你的电话intMatrixAll改变:
Finally, you need to change your call to intMatrixAll to:
intMatrixAll(testArrRow, testArrCol, &testMatrix);
之所以是,仅C通过支持按值传递和按值不支持调用的函数中调用者改变一个变量的值。
The reason why is that C only supports pass-by-value and pass-by-value does not support the called function changing the value of a variable in the caller.
为了修改主叫变量的值,你需要一个指针传递给变量,然后让被调用函数取消对它的引用。
In order to modify the value of a variable in the caller, you need to pass a pointer to the variable and then have the called function dereference it.
这篇关于当函数修改动态分配的二维数组C.分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!