Skip to main content
nanayakkaraan
Associate III
February 25, 2011
Question

Handling 2D arrays in C

  • February 25, 2011
  • 1 reply
  • 709 views
Posted on February 25, 2011 at 12:51

Handling 2D arrays in C

    This topic has been closed for replies.

    1 reply

    Tesla DeLorean
    Guru
    May 17, 2011
    Posted on May 17, 2011 at 14:25

    Well you'd better have them be of fixed dimensions if you want it to be ''easy'', otherwise you will have to manipulate and index into them manually (ie compute the position of the row/column within a flat pointer).

    In Microsoft C this is passed as a pointer, it does not copy the structure onto the stack.

    void test(int array[3][3])

    {

      int i, j;

      for(i=0; i<3; i++)

        for(j=0; j<3; j++)

          printf(''%d\n'',array[i][j]);

      putchar('\n');

    }

    int main()

    {

      int i, j;

      int inputarray[3][3];

      for(i=0; i<3; i++)

        for(j=0; j<3; j++)

          inputarray[i][j] = i + j*3;

      for(i=0; i<3; i++)

        for(j=0; j<3; j++)

          printf(''%d\n'',inputarray[i][j]);

      putchar('\n');

      test(inputarray);

      return(1);

    }

    I'd be tempted to do this as a structure myself, especially if dimensions have to follow the array around to other procedures/functions.

    void test(int *array, int x, int y)

    {

      int i, j;

      for(i=0; i<x; i++)

        for(j=0; j<y; j++)

          printf(''%d\n'',array[(i * y)  + j]); // array[i][j]

      putchar('\n');

    }

    #define ARRAY_X 3

    #define ARRAY_Y 5

    int main()

    {

      int i, j, k;

      int inputarray[ARRAY_X][ARRAY_Y];

      k = 0;

      for(i=0; i<ARRAY_X; i++)

        for(j=0; j<ARRAY_Y; j++)

          inputarray[i][j] = k++;

      for(i=0; i<ARRAY_X; i++)

        for(j=0; j<ARRAY_Y; j++)

          printf(''%d\n'',inputarray[i][j]);

      putchar('\n');

      test((void *)inputarray, ARRAY_X, ARRAY_Y);

      return(1);

    }

    Tips, Buy me a coffee, or three.. PayPal Venmo (See Profile) Up vote any posts that you find helpful, it shows what's working..