How to pass 2D array to function

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • AmberJain
    Recognized Expert Contributor
    • Jan 2008
    • 922

    How to pass 2D array to function

    Well, I got this question as an assignment-------->

    Write a C program to pass a 2D array (of characters and integers both) to a function?

    Thanks in advance to everyone....... ............
    ambrnewlearner
  • gpraghuram
    Recognized Expert Top Contributor
    • Mar 2007
    • 1275

    #2
    Originally posted by ambrnewlearner
    Well, I got this question as an assignment-------->

    Write a C program to pass a 2D array (of characters and integers both) to a function?

    Thanks in advance to everyone....... ............
    ambrnewlearner

    When passing a 2 d array to a function then you should pass the array as well as the size of the array.
    But what did u try anything on this
    Raghuram

    Comment

    • AmberJain
      Recognized Expert Contributor
      • Jan 2008
      • 922

      #3
      Originally posted by gpraghuram
      When passing a 2 d array to a function then you should pass the array as well as the size of the array.

      ???????????? But what did u try anything on this

      Raghuram
      _______________ _______________ _______________ __________
      What do you mean by : "But what did u try anything on this"

      ambrnewlearner
      _______________ _______________ _______________ __________

      Comment

      • gpraghuram
        Recognized Expert Top Contributor
        • Mar 2007
        • 1275

        #4
        I was asking , did u write any code for this?


        Raghuram

        Comment

        • romcab
          New Member
          • Sep 2007
          • 108

          #5
          You need the index in passing 2D array. You can refer to this simple code.

          [CODE=cpp]#include "stdafx.h"

          void Accept(int arr[][2], int row, int col);

          int _tmain(int argc, _TCHAR* argv[])
          {
          int myArray[3][2] = { {0,0}, {1,1}, {2,2} };
          Accept(myArray, 3, 2);
          return 0;
          }

          void Accept(int arr[][2], int row, int col )
          {
          int i, j;
          for ( i = 0; i < row; i++ )
          for ( j = 0; j < col; j++ )
          arr[i][j] = 5;
          }[/CODE]
          Last edited by Ganon11; Feb 14 '08, 03:28 AM. Reason: Please use the [CODE] tags provided.

          Comment

          • AmberJain
            Recognized Expert Contributor
            • Jan 2008
            • 922

            #6
            Originally posted by gpraghuram
            I was asking , did u write any code for this?


            Raghuram
            _______________ _______________ _______________ _______________
            Well, [quite foolishly] my answer is NO. Actually I am still learning functions in C and don't have a good command over functions. I missed some of my lectures at college [I was ill] and therefore don't know much about functions and later on my faculty couldnot explain it to me perfectly and so I posted this question on thescripts.
            HOPE that someone explains me the complete concept of this question

            _______________ _______________ _______________ _______________ _

            Comment

            • AmberJain
              Recognized Expert Contributor
              • Jan 2008
              • 922

              #7
              Originally posted by romcab
              You need the index in passing 2D array. You can refer to this simple code.

              [CODE=cpp]#include "stdafx.h"

              void Accept(int arr[][2], int row, int col);

              int _tmain(int argc, _TCHAR* argv[])
              {
              int myArray[3][2] = { {0,0}, {1,1}, {2,2} };
              Accept(myArray, 3, 2);
              return 0;
              }

              void Accept(int arr[][2], int row, int col )
              {
              int i, j;
              for ( i = 0; i < row; i++ )
              for ( j = 0; j < col; j++ )
              arr[i][j] = 5;
              }[/CODE]
              _______________ _______________ _______________ ___________

              <---------newbie here--------->
              Can you please explain it in more detail
              _______________ _______________ _______________ ___________

              Comment

              • weaknessforcats
                Recognized Expert Expert
                • Mar 2007
                • 9214

                #8
                Please read this:
                Originally posted by weaknessforcats
                First, there are only one-dimensional arrays in C or C++. The number of elements in put between brackets:
                [code=c]
                int array[5];
                [/code]

                That is an array of 5 elements each of which is an int.

                [code=c]
                int array[];
                [/code]

                won't compile. You need to declare the number of elements.

                Second, this array:
                [code=c]
                int array[5][10];
                [/code]

                is still an array of 5 elements. Each element is an array of 10 int.

                [code=c]
                int array[5][10][15];
                [/code]

                is still an array of 5 elements. Each element is an array of 10 elements where each element is an array of 15 int.


                [code=c]
                int array[][10];
                [/code]

                won't compile. You need to declare the number of elements.

                Third, the name of an array is the address of element 0
                [code=c]
                int array[5];
                [/code]

                Here array is the address of array[0]. Since array[0] is an int, array is the address of an int. You can assign the name array to an int*.

                [code=c]
                int array[5][10];
                [/code]

                Here array is the address of array[0]. Since array[0] is an array of 10 int, array is the address of an array of 10 int. You can assign the name array to a pointer to an array of 10 int:
                [code=c]
                int array[5][10];

                int (*ptr)[10] = array;
                [/code]

                Fourth, when the number of elements is not known at compile time, you create the array dynamically:

                [code=c]
                int* array = new int[value];
                int (*ptr)[10] = new int[value][10];
                int (*ptr)[10][15] = new int[value][10][15];
                [/code]

                In each case value is the number of elements. Any other brackets only describe the elements.

                Using an int** for an array of arrays is incorrect and produces wrong answers using pointer arithmetic. The compiler knows this so it won't compile this code:

                [code=c]
                int** ptr = new int[value][10]; //ERROR
                [/code]

                new returns the address of an array of 10 int and that isn't the same as an int**.

                Likewise:
                [code=c]
                int*** ptr = new int[value][10][15]; //ERROR
                [/code]

                new returns the address of an array of 10 elements where each element is an array of 15 int and that isn't the same as an int***.

                With the above in mind this array:
                [code=cpp]
                int array[10] = {0,1,2,3,4,5,6, 7,8,9};
                [/code]
                has a memory layout of

                0 1 2 3 4 5 6 7 8 9

                Wheras this array:
                [code=cpp]
                int array[5][2] = {0,1,2,3,4,5,6, 7,8,9};
                [/code]
                has a memory layout of

                0 1 2 3 4 5 6 7 8 9

                Kinda the same, right?

                So if your disc file contains

                0 1 2 3 4 5 6 7 8 9

                Does it make a difference wheher you read into a one-dimensional array or a two-dimensional array? No.

                Therefore, when you do your read use the address of array[0][0] and read as though you have a
                one-dimensional array and the values will be in the correct locations.
                and then post again if you are still stuck.

                Comment

                • AmberJain
                  Recognized Expert Contributor
                  • Jan 2008
                  • 922

                  #9
                  Originally posted by weaknessforcats
                  Please read this:

                  YOUR REPLY

                  and then post again if you are still stuck.
                  _______________ _______________ _______________ ____________
                  THANKS weaknessforcats ............... .........
                  This is certainly one of best and brief tutorial on arrays. But I'm stuck with functions and not arrays in my question "WRITE A PROGRAM TO PASS A 2D ARRAY TO A FUNCTION". I missed my lecture on functions and therefore if someone can guide me on functions or recommend a good book as a "self tutorial" for functions, then probably my problem will be solved....

                  Comment

                  • Simonius
                    New Member
                    • Feb 2008
                    • 47

                    #10
                    Code: ( c )
                    1. int array[];
                    won't compile. You need to declare the number of elements.
                    It'll compile if you fill it in like int array[]={0,1,2,3,4,5,6 ,7,8,9};

                    Comment

                    • weaknessforcats
                      Recognized Expert Expert
                      • Mar 2007
                      • 9214

                      #11
                      Originally posted by Simonius
                      It'll compile if you fill it in like int array[]={0,1,2,3,4,5,6 ,7,8,9};
                      Of course it will, you specified the number of elements. This is initialization syntax only. The compiler will create an array for that number of elements and intialize each element to its respective value.

                      Originally posted by ambrnewlearner
                      But I'm stuck with functions and not arrays in my question "WRITE A PROGRAM TO PASS A 2D ARRAY TO A FUNCTION". I
                      Read that tutorial again and tattoo on your head: The name of the array is the address of element 0.

                      This array:
                      [code=c]
                      int arr[3][4][5];
                      [/code]

                      can be passed to a function:
                      [code=c]
                      func(arr);
                      [/code]

                      if the argument to func() is a pointer to a [4][5] array.

                      But if the func argiument is a pointer to an [5] array of int, you need to pass the &arr[0][0].

                      But if the func argiument is a pointer to an int, you need to pass the &arr[0][0][0].

                      As you omit dimensions you need to add arguments to funct() since the "array-ness" is lost on the call. This is called decay of array and this occurs whenever an array is pass to a function. From inside the function all you see is an address and not an array.

                      Comment

                      • cube
                        New Member
                        • Feb 2008
                        • 18

                        #12
                        My congratulations "weaknessforcat s".
                        Functions are troubling me too and you made everything, more than crystal clear!

                        Comment

                        • cjava
                          New Member
                          • Feb 2008
                          • 3

                          #13
                          Originally posted by weaknessforcats
                          Of course it will, you specified the number of elements. This is initialization syntax only. The compiler will create an array for that number of elements and intialize each element to its respective value.



                          Read that tutorial again and tattoo on your head: The name of the array is the address of element 0.

                          This array:
                          [code=c]
                          int arr[3][4][5];
                          [/code]

                          can be passed to a function:
                          [code=c]
                          func(arr);
                          [/code]

                          if the argument to func() is a pointer to a [4][5] array.

                          .
                          Cool ..

                          Let me make some other points clear ..

                          The problem is to pass a 2 dimensional array to a function.

                          From your question I presume you want to pass the array by reference because only that would make sense.

                          First of all in order to do that you need to understand certain nuances for passing an array.

                          when you declare

                          int a [5]

                          then an memory of 5 contiguous spaces is first allocated and given an integer view.

                          Then this integer memory is assigned to a.

                          hence typing simply a refers to the first location of the memory.

                          *a would be equivalent to a[0].

                          However when it comes to Multidimensiona l arrays C does not have great support for them.

                          They are usually visualized as array of arrays.

                          Code:
                          for ex. 
                          
                           [ ] -> [Row 1]
                           [ ] -> [Row 2]
                           [ ] -> [Row 3]
                          now..

                          there are two ways to declare an 2D array :
                          Code:
                          a) int a[rows] [cols]
                          b )Simulated using double pointers.
                          So its important to know how you 2D array is declared.

                          Given all these Here are the ways to pass it to the functions :

                          let fn be the function receiving the 2D array.

                          Then

                          Code:
                          int fn (int a[][cols]);
                          int fn ( int a[rows][cols]);
                          int fn(int *ptr,int rows,int cols) 
                          int fn (int **ptr ) (Only if you declared using Simulated methd)
                          Some word of caution

                          Code:
                          int a[rows][cols]
                          a = *a = adrress of the first element of the first row.
                          so never try to use **a if you use the above method to declare 2D arrays.
                          you can use int *ptr = a to pass the array address.
                          Two dimensional array is not double pointer.

                          Comment

                          • weaknessforcats
                            Recognized Expert Expert
                            • Mar 2007
                            • 9214

                            #14
                            There is now an article about this in the C/C++ HowTos forum.

                            http://www.thescripts.com/forum/thread772412.html.

                            Comment

                            Working...