When I am trying to pass two dimensional array as a parameter In C,
void PrintTriangle(int *triangle)
It's doesn't works for me why ?
When I am trying to pass two dimensional array as a parameter In C,
void PrintTriangle(int *triangle)
It's doesn't works for me why ?
You must specify the dimension of the outermost array when passing multidimensional arrays as parameters
Something like this:-
void PrintTriangle(int pascalTriangle[][5]);
Calling PrintTriangle(pascalTriangle);
like this is wrong as your function PrintTriangle()
is expecting a pointer to integer.
Calling your function as
PrintTriangle(pascalTriangle);
is wrong. Because PrintTriangle()
expecting a pointer to integer as its argument and pascalTriangle
(after decaying) is of type int(*)[5]
.Also you must have to pass the number of rows and columns (as arguments) in array pascalTriangle
. Prototype for this function should be
void PrintTriangle(int row, int col, int *triangle);
and a call to it may be
PrintTriangle(5, 5, &pascalTriangle[0][0]);
Here's how I memorized passing multidemensional arrays as parameters. This might be a little childish but works for me.
Suppose You have an array defined
int numbers[3][4];
and you want to pass it to function.
To do it correctly I answer series of questions:
1) What do I want to pass to function? An array.(in this case numbers
).
2) What's numbers
? Numbers
is an address of its first element(without going into details);
3)What's the first element of numbers
?(in this case it's an array of 4 integers
)
4) So what I want as function formal parameter is a pointer to answer from step 3
:
int (*pointer)[4]
It might be slow and looks unprofessional but you can ask the same question on array of every dimension you can think of. It's also useful to ask yourself that when not passing whole array but one of subarrays.
Hope it helps you as it helped me.