C. Segmentation Fault when function modifies dynamically allocated 2d array

前端 未结 3 741
野的像风
野的像风 2020-12-06 15:21

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 fu

3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-06 16:17

    Test matrix is still NULL. You need to return the newly allocated pointer from intMatrixAll(). Either return the value from the function, or pass in the address of testMatrix so it can be set.

    #include 
    #include 
    #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

提交回复
热议问题