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

前端 未结 3 745
野的像风
野的像风 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 15:52

    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)
    

    Inside intMatrixAll, you'll now need to change matrix to *matrix (and for when you are indexing it, you'll want (*matrix)[...].

    Finally, you need to change your call to intMatrixAll to:

    intMatrixAll(testArrRow, testArrCol, &testMatrix);
    

    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.

提交回复
热议问题