How to pass statically allocated 2D array to a function in C

2

I am modifying some code to move away from using dynamic memory allocation because it will be embedded on a system. I am statically allocating memory for my objects then assigning pointers to these. I need to be able to pass pointers to 2D arrays to functions, but am finding that this is not working, where it was with dynamically allocated arrays.

Here is some example code. Passing the dynamically allocated array x to my function works no problem.

However it fails with the statically allocated array, y in the function "func" where it tries writing to the first element of the array "array[i][j] = i * j". The error message is "Access violating writing location 0x00000000. My question is why, and what I can do to resolve this?

void func(int** array, int rows, int cols)
{
    for (int i = 0; i < rows; i++) for (int j = 0; j < cols; j++)array[i][j] = i * j;
}

static int y[ROWS][COLS];

int main()
{
    int rows, cols, i;
    int **x;
    rows = ROWS; cols = COLS;
    // Dynamic allocation of X:
    x = malloc(rows * sizeof *x);
    for (i = 0; i < rows; i++)
    {
        x[i] = malloc(cols * sizeof *x[i]);
    }
    // The following works no problem:
    func(x, rows, cols);
    // However doing it with the statically allocated array fails.
    func(y, rows, cols);

    /* deallocate the array */
    for (i = 0; i < rows; i++)
    {
        free(x[i]);
    }
    free(x);
}
c
pointers
multidimensional-array
function-parameter
asked on Stack Overflow Nov 15, 2019 by bgarrood • edited Nov 15, 2019 by bgarrood

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0