Using realloc on a 2D array c

前端 未结 3 962
执笔经年
执笔经年 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:22

    In c the variables are passed by value, because of this the iMat inside the modifyMatrix() is not modifying the one in the caller function.

    You need to pass the address of iMat instead

    void modifyMatrix(int ***iMat, int iRow, int iRow2, int iCol)
    {
        int i;
        int **safe;
    
        safe = realloc(*iMat, iRow2 * sizeof(int *));
        if (safe == NULL)
            return;
        *iMat = safe;
    
        for (i = 0 ; i < iRow ; i++)
        {
            int *keep_old_pointer;
            keep_old_pointer = realloc(safe[i], iCol * sizeof(int));
            if (keep_old_pointer == NULL)
                do_something_allocation_failed();
            safe[i] = keep_old_pointer;
        }
    
        for (int i = iRow ; i < iRow2 ; ++i)
            safe[i] = malloc(iCol * sizeof(int));
    }
    

    Also, don't assign NULL to every element and then try to realloc() because if realloc() makes sense in this situation then you are overwriting the pointers with NULL without freeing them.

    And don't overwrite the realloc()ed pointer before checking if the allocation was succesfull, because if it fails you wont be able to free the previous pointer because you would have lost reference to it, causing a memory leak.

提交回复
热议问题