c - getting error in gcc but runs successfully anyway -


#include<stdio.h> void display(int *q,int,int); int main(){ int a[3][4]={              2,3,4,5,              5,7,6,8,              9,0,1,6             }; display(a,3,4); return 0; } void display(int *q,int row,int col){   int i,j;       for(i=0;i<row;i++){            for(j=0;j<col;j++){                  printf("%d",*(q+i*col+j));                  }  printf("\n"); } printf("\n"); } 

why code show warning in gcc "passing argument 1 of 'display' incompatible pointer type display(a,3,4)"?...runs anyway curious know error..if tell grateful..

the rule of "array decay" means whenever use array name a part of expression, "decays" pointer first element.

for 1d array, pretty straight forward. array int [10] decay type int*.

however, in case of two-dimensional arrays, first element of 2d array 1d array. in case, first element of int a[3][4] has array type int [4].

the array decay rule gives pointer such array, array pointer, of type int (*)[4]. type not compatible type int* function expects.

however, sheer luck, appear the array pointer , plain int pointer have same representation on system, , happen hold same address, code works. shouldn't rely on though, not well-defined behavior , there no guarantee work.


you should fix program in following way:

#include <stdio.h>  void display (int row, int col, int arr[row][col]);  int main() {   int a[3][4]=   {     {2,3,4,5},     {5,7,6,8},     {9,0,1,6},   };    display(3, 4, a);   return 0; }  void display (int row, int col, int arr[row][col]) {   for(int i=0; i<row; i++)   {     for(int j=0; j<col; j++)     {       printf("%d ", arr[i][j]);     }     printf("\n");   }   printf("\n"); } 

here array type function parameter silently "get adjusted" compiler pointer first element, int(*)[4], matches what's passed function caller.


Comments