Monday, July 2, 2018

C program passing 2D array

/* When both dimensions are available globally (either as a macro or as a global constant).*/
#include <stdio.h>
const int M = 3;
const int N = 3;

void print(int arr[M][N])
{
    int i, j;
    for (i = 0; i < M; i++)
      for (j = 0; j < N; j++)
        printf("%d ", arr[i][j]);
}

int main()
{
    int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    //int arr[][N] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};  // error : variable-sized object may not be initialized
    print(arr);
   // print(&arr[0][0]); //works with warning expected 'int(*)[(sizetype)N]' but argument is of type ' int *'
    //print((int *)arr); //works with warning expected 'int(*)[(sizetype)N]' but argument is of type ' int *'
   // print((int*)arr[0][0]); // error : abrupt termination of program
    return 0;
}

No comments:

Post a Comment

How can I run a C++ program directly from Windows?

How-can-I-run-a-C-program-directly-from-Windows