Function passing of multidimensional array in c -
#include <stdio.h> void spiral(int a[10][10]) { printf("%d", a[1][3]); } int main() { int r, c, j, i; scanf("%d%d", &r, &c); int a[r][c]; (i = 0; < r; i++) (j = 0; j < c; j++) { scanf("%d", &a[i][j]); } spiral(a); return 0; } when give 3 x 6 array
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 the output 14, while should 10
how fix issue?
if enter 3 , 6 r , c (respectively) type of a not int[10][10] (or int(*)[10] spiral argument is), it's int[3][6]. memory layout different arrays, leading undefined behavior.
you can solve passing size along function, , using in declaration of array:
void spiral(const size_t r, const size_t c, int (*a)[c]) { ... } call expected:
spiral(r, c, a); as noted using int a[r][c] argument might easier read , understand, gives false impression a array. it's not. compiler treats argument pointer array of c integers, i.e. int (*a)[c].
this makes me little conflicted... on 1 hand i'm making things easier read , understand (which means easier maintain), on other hand newbies wrong , think 1 can pass array intact when in fact decays pointer can lead misunderstandings.
Comments
Post a Comment