函数修改动态分配的二维数组时出现分段错误

函数修改动态分配的二维数组时出现分段错误

本文介绍了C. 函数修改动态分配的二维数组时出现分段错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要的是一个函数,可以像这样修改给定的指向二维矩阵的指针:

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

为什么我会出错?

推荐答案

因为修改 intMatrixAll() 中的矩阵不会修改 main() 中的 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 中,您现在需要将 matrix 更改为 *matrix(并且在索引它时,您需要 (*matrix)[...].

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. 函数修改动态分配的二维数组时出现分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 08:51