You are getting confused because you are using different types when there's no need for such. Arrays follow the same rules of indirection as any other type. If you would allocate a plain int
dynamically, you would write int* x = malloc(sizeof(*x));
. Simply do the very same thing when it comes to arrays. Don't confuse things by mixing in the "arrays decay to pointers" rule.
So we have int input[2][100]
, very straight-forward, it is a plain 2D array. Now if you want to allocate that dynamically, you will need a pointer to such an array:
int (*pIn)[2][100]; // pointer to an array of int [2][100].
pIn = malloc(sizeof(*pIn));
And the whole program would then be:
#include <stdlib.h>
void Process (size_t num, int pInput[num][100])
{
}
int main (void)
{
int (*pIn)[2][100];
int input[2][100] = {0};
pIn = malloc(sizeof(*pIn));
if(pIn == NULL)
{
// error handling
return 0;
}
Process(2, *pIn);
Process(2, input);
free(pIn);
return 0;
}
Comments:
size_t
is the most correct type to use for array sizes, as it is the type returned by the sizeof
operator. So it is just an unsigned integer with a fancy name.
int pInput[num][100]
in the function will actually decay into an array pointer to an array of 100 int. You don't need to know that to use it though, simply use pInput[x][y]
and pretend it is a 2D array. The important thing here is to understand that the array is not passed by value.
- The correct form of main is
int main (void)
.
- Casting the result of malloc is pointless.
- Always check the result of malloc and remember to clean up allocated data.