Using realloc on a 2D array c

前端 未结 3 963
执笔经年
执笔经年 2020-12-20 09:26

I\'m kinda new to C sorry if my questions is somewhat vague;

I need to use realloc on a 2D array without losing it\'s previous data, I have this function in my progr

3条回答
  •  青春惊慌失措
    2020-12-20 10:09

    On success, realloc frees the pointer you pass to it and returns a pointer to the newly allocated memory. You're getting "junk values" because dereferencing a pointer to freed memory is undefined behavior.

    It's not pretty, but the way to fix this (as another answer pointed out) is to pass a triple pointer (int***). That way the function can modify the original value of the pointer. This is how you simulate reference semantics in C, which is a strictly "pass by value" language.

    void modifyMatrix(int ***iMat, int iRow, int iRow2, int iCol)
    {
        int i;
        int **newMatrix = realloc(*iMat, iRow2 * sizeof(int*));
        if (newMatrix == NULL) {
               /* handle realloc error here */
        }
        else {
              *iMat = newMatrix; /* assign pointer to the new memory */
        }
    
        for(i=iRow; i

    You've also got to add some error checking. If realloc fails and returns a NULL pointer, you've just created a memory leak: you no longer have the previous value of the pointer.

    Note that I removed all of your casts. It's bad practice to cast the return of malloc and friends in C.

提交回复
热议问题