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

标签 c arrays memory pointers

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

void intMatrixAll(int row, int col, int **matrix);

现在,函数应该分配内存并且可以使用矩阵。行和列在运行时给出。

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

为什么会出现错误?

最佳答案

测试矩阵仍然是 NULL。您需要从 intMatrixAll() 返回新分配的指针。要么从函数返回值,要么传入 testMatrix 的地址以便对其进行设置。

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

关于C. 函数修改动态分配的二维数组时的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1918120/

相关文章:

C-将txt读入txt文件

使用指针反转字符串的 C 代码

java - 在 Java 中将 List<Object> 转换为 String[]

c++ - "Private memory"尽管对象被破坏,但捕获 bad_alloc 后未释放

memory - x86 push/pop 可以小于 4 个字节吗?

c - 为什么回调函数中的值不同 - 不好?

c - 就绪队列模拟器 - [错误] 'sigINT' 和 'sigQUIT' 未声明(首次在此函数中使用)

c - Ansi-C C99 接口(interface)与结构

javascript - 在键上加入数组

linux - 如何获取 freeRTOS 中进程的内存使用情况