Advertisement
drankinatty

Understanding Array/Pointer Conversion

Jan 2nd, 2019
301
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.51 KB | None | 0 0
  1. /* see: C11 Standard - 6.3.2.1 Other Operands - Lvalues, arrays, and function designators(p3)
  2.  *      http://port70.net/~nsz/c/c11/n1570.html#6.3.2.1p3
  3.  */
  4. #include <stdio.h>
  5.  
  6. void printmyarr (int pt[][4], int nptrs)
  7. {
  8.     int nelem = sizeof *pt/sizeof **pt;     /* number of int per-array */
  9.    
  10.     for (int i = 0; i < nptrs; i++) {       /* iterate each row */
  11.         for (int j = 0; j < nelem; j++)     /* iterate each col */
  12.             printf (" %4d", pt[i][j]);      /* output int */
  13.         putchar ('\n');                     /* tidy up with newline */
  14.     }
  15. }
  16.  
  17. void printwptr (int (*pt)[4], int nptrs)
  18. {
  19.     int nelem = sizeof *pt/sizeof **pt;     /* number of int per-array */
  20.    
  21.     while (nptrs--) {               /* iterate nptrs times */
  22.         int *p = *pt++,             /* initialize p to row, advance pt */
  23.             n = nelem;              /* initialize n to nelem */
  24.         while (n--)                 /* iterate n times */
  25.             printf (" %4d", *p++);  /* output element, advance to next */
  26.         putchar ('\n');             /* tidy up with newline */
  27.     }
  28. }
  29.  
  30. int main (void) {
  31.    
  32.     int myarr[][4]  =  {{  12,   16,   19,   20},
  33.                         {   5,   99,  102,  200},
  34.                         {  12,   20,   25,  600},
  35.                         {  65,   66,  999, 1000}};
  36.  
  37.     puts ("print with indexes:");
  38.     printmyarr (myarr, sizeof myarr/sizeof *myarr);
  39.    
  40.     puts ("\nprint with pointers:");
  41.     printwptr (myarr, sizeof myarr/sizeof *myarr);
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement