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

前端 未结 3 746
野的像风
野的像风 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:18

    Please see here for a discussion on something similar. The reason it seg faulted is because you are not passing the pointer-to-pointer of int's back out of the function intMatrixAll to the main routine. In other words, you are passing in a parameter of double pointer to int's by value, not by reference, and tried to access testMatrix when it was in fact still NULL.

    So you need to add another level of indirection, i.e. * and use that indirection as a means to alter the double pointers to be mallocd and for the main routine to see that testMatrix has indeed being allocated.

    See R. Samuel Klatchko's answer above.

    As a general rule, if you want to pass a pointer to something as a parameter by reference, add another level of indirection. In your case, you pass in a double pointer to int, make the parameter as a triple pointer in the function.

    int **testMatrix;
    void intMatrixAll(int row, int col, int ***matrix){
      // In here use this (*matrix)
    }
    
    // Then the calling of the function would look like this
    intMatrixAll(testArrRow, testArrCol, &testMatrix); 
    
    // Note the ampersand above to treat this double pointer passed in by reference
    

    Hope this helps and make sense, Best regards, Tom.

提交回复
热议问题