Thread: Passing two dimensional array to function using pointer

  1. #1
    Registered User
    Join Date
    Oct 2012
    Posts
    14

    Passing two dimensional array to function using pointer

    This code shows error message why?
    Code:
    #include<stdio.h>
    void love(char *arr[5][5]);
    int main()
    {char arr[5][5];
      int i,j;
      
     for(i=0;i<5;i++)
     {
         
         for(j=0;j<5;j++)
         {
         arr[i][j]='*';
         }
     }
     love(&arr);
    }
    
    void love(char *arr[5][5])
    {int i, j;
    for(i=0;i<5;i++)
     {
         for(j=0;j<5;j++)
         {
         printf("%c",*arr[i][j]);
         }
     }
     
    }

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,323
    Because the parameter is actually a pointer to an array of 5 pointers to char. What you really want is:
    Code:
    void love(char (*arr)[5][5]);
    Of course, this also means that you should change this:
    Code:
    printf("%c",*arr[i][j]);
    to:
    Code:
    printf("%c", (*arr)[i][j]);
    You probably don't need to pass a pointer to the array of arrays of char. Rather, you can pass a pointer to an array of char instead:
    Code:
    void love(char (*arr)[5]);
    /* ... */
    love(arr);
    then:
    Code:
    printf("%c", arr[i][j]);
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,694
    And after doing what laserlight said do not forget to structure your indentation .

    Also notice that we usually write
    Code:
    int main(void)
    {
           ...
           return 0;
    }

  4. #4
    Registered User
    Join Date
    Oct 2012
    Posts
    14
    Problem solved thanks.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 11
    Last Post: 12-30-2009, 04:04 PM
  2. Passing a pointer to two-dimension array in a function
    By E_I_S in forum C++ Programming
    Replies: 11
    Last Post: 06-19-2008, 09:57 AM
  3. Passing 2 dimensional array to a function
    By salvadoravi in forum C Programming
    Replies: 10
    Last Post: 01-16-2008, 12:38 AM
  4. Passing pointer to array to a function
    By Tojam in forum C Programming
    Replies: 1
    Last Post: 10-09-2002, 09:24 PM
  5. ? passing multi dimensional array to function
    By rc7j in forum C++ Programming
    Replies: 1
    Last Post: 02-10-2002, 02:19 AM