c - Acessing a 2D array inside a function -
i have function accepts int* pinput[] argument.
void process(int* pinput[], unsigned int num); i have call function via 2 methods as
main() { int *pin[2]; int input[2][100] = {0}; pin[0] = ( int* )malloc( 100 * sizeof( int) ); pin[1] = ( int* )malloc( 100 * sizeof( int) ); process( pin, 2 ); process( ( int** )input, 2 ); } then how can access each value of pinput inside function 'process'?i cannot access directly pin[0][0].
how can access each value of pinput inside function 'process'?i cannot access directly pin[0][0].
no! can access way: pinput[0][0] if input pass pin. because pin array of int*s i.e. it's of type int *[n] each of element pointing array of ints. decay int**.
however, if want pass input, 2d array of ints, you've more since 2d array doesn't decay double pointer, t** pointer array, t (*) [n]. because array decay not recursive, happens first level. alternatively, can (live example)
pin[0] = input[0]; pin[1] = input[1]; and pass pin process. here pin surrogate input , needs have many elements input, not elegant solution. better way pass input, when know dimensions during compile-time is
void process(int (*pinput)[100], size_t rows) { } void process(int input [2][100], size_t rows) { } /* these 2 same; compiler never sees `2`. input's type int(*)[100] */ read on array decay understand situation better.
aside
- do cast result of malloc? no, not need cast return value of
mallocin c. - what should main() return in c , c++? return type of
mainshouldint.
Comments
Post a Comment