Passing a two dimensional array to a function

Discussion in 'C' started by bashamsc, Dec 18, 2007.

  1. bashamsc

    bashamsc New Member

    Joined:
    May 22, 2007
    Messages:
    51
    Likes Received:
    7
    Trophy Points:
    0
    Location:
    chennai
    I tried two methods for this and it worked.

    First Method :

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

    Second Method :

    Code:
    #include<stdio.h>
    
    void fun(int a[3][3],int col , int row)
    {
    int i,j;
    for(i=0;i<3;i++)
    {
    for(j=0;j<3;j++)
    {
    printf(" %d\t",a[i][j]);
    }
    printf("\n\n");
    }
    }
    
    
    main()
    {
    
    int arr[3][3] = {{1,2,3},
                     {4,5,6},
                     {7,8,9}};
    printf("%u\n",arr);
    fun(arr,3,3);
    
    }
    
     
    Last edited by a moderator: Dec 18, 2007
  2. kv.santosh

    kv.santosh New Member

    Joined:
    Dec 13, 2007
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    Software Engineer
    Location:
    Hyderabad
    Home Page:
    http://kv.santosh.googlepages.com/
    Hi,

    just a small correction...ur function should rather used passed row an col values insetad of hardcoding them...somehting like this....

    Code:
    void fun(int *a,int col , int row)
    {
    int i,j;
    for(i=0;i<col ;i++)
    {
    for(j=0;j<row;j++)
    {
    printf(" %d\n",*(a+j));
    }
    a=a+row;
    }
    }
     
    Last edited by a moderator: Dec 18, 2007
  3. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83
  4. Salem

    Salem New Member

    Joined:
    Nov 15, 2007
    Messages:
    133
    Likes Received:
    5
    Trophy Points:
    0
    Occupation:
    Please don't PM me for 1:1 support.
    Learning how to indent code as well would be a priority as well.

    In response to "method 1".
    http://c-faq.com/aryptr/ary2dfunc2.html

    > I tried two methods for this and it worked.
    Be careful of thinking that "works for me" is any substitute for knowing what is guaranteed by the standard. There are hundreds (possibly thousands) of compilers out there, and you've just tested one of them with a single experiment.
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice