So I was writing some C code, pretty simple code. I had to pass a matrix to a function. The matrix had been globally defined as arr[100][100]. But the actual size of the matrix was stored in 2 vars m, n. Now when defining the function if I do like this:

void fun(int a[][n])

The code doesn't work as expected but when defined as:

void fun(int a[][100])

Works perfectly.

I have no idea why this is happening, any insight will be very helpful.

  • 9
    One word: constant.

    In the second case compiler can produce one and only definition but in the first case it cannot because N is not a constant and cannot be calculated at compile time.
  • 7
    In C array sizes have to be constant for the compiler to know how big that array is. try to put a 'const' before your variable that defines the size.
  • 3
    you can use const keyword to define variable 'n'.
    const int n = 100;
    initializing const variable is compulsary
  • 5
    If you cannot use const you could fake it by defining the function as one dimensional and calculating the index by multiplying the first dimension by n and adding the second.

    Its not very elegant code but it works.

    The underlying problem is that thats basically what the compiler converts your code to, but without const as mentioned, the compiler does not know how long it should jump to reach the next row. So you have to do the calculation manually.
  • 3
    @Voxera or one can just use normal pointers. 🤷‍♀
  • 2
    @irene sure, but you end up with a similar problem. An array is just a pointer with some helpers, using a raw pointer does not remove the need to calculate the offset.

    At least as far as I remember, but its been 15 years ;) I might have missed something.
  • 1
    @Voxera ehm... You can do <pointer>[m][n] just fine. 🤔 The only thing to consider is to not go outside of the allocated memory.

    EDT: the top array's contents should be of a type[100] so that the size of each element would be calculated correctly in a plain chunk of memory.
  • 2
    @irene Ok, but my case was for the situation where the 2d array does not have a constant size but can be sent arrays of different sizes.

    In which case the function cannot know the correct size.

    Nv. Just me rambling about things I have not used for a long time :P
Your Job Suck?
Get a Better Job
Add Comment