1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Passing Pointer-To-An-Array Through Function

Discussion in 'C' started by tppramod, Jan 1, 2009.

  1. tppramod

    tppramod New Member

    Joined:
    Jan 1, 2009
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    Hi!
    I want to pass a pointer-to-an-array through a function and print the data in the array. I dont know why its giving junks...! Please tell me where i am wrong and how to achieve this? Please note that i want to do this only through function as shown in the code. Pls. help.

    Here is the code:
    Code:
     
    char *NameList[] = { "Father", "Mother"};
    main()
    {
      int i;
      Function(NameList);  //Pointer To The Array Is Passed Through The Function
    }
     
    Function(char *ArrayPointer)
      {
        int i;
        for (i=0; i < 2; i++)
          {
            printf("\nName: %s %s", ArrayPointer[i]);  // Why It is not fetching the data?
          }
      }
     
    Last edited by a moderator: Jan 1, 2009
  2. Jadav Rakesh C.

    Jadav Rakesh C. New Member

    Joined:
    Nov 15, 2007
    Messages:
    17
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    VC++ Developer
    Location:
    Surat
    Hi..tppramod,

    First let me clarify you that Array always passes to functions through pointer,the base address of array...As you are beginner,I have two solutions for you.

    Solution 1::
    Code:
    char *pNameList = 0;
    char NameList[][10] = { "Father", "Mother"};
    
    void Function(char *ArrayPointer)
    {
        int i;
        for (i=0; i < 2; i++)
          {
            printf("\nName: %s", ArrayPointer++);  
          }
    }
    void main()
    {
      int i;
      pNameList = &NameList[0][10];
      Function(pNameList);  //Pointer To The Array Is Passed Through The Function
    }
    
    Solution 2::
    Code:
    
    char NameList[][10] = { "Father", "Mother"};
    
    void Function(char ArrayPointer[][10])
    {
        int i;
        for (i=0; i < 2; i++)
          {
            printf("\nName: %s", ArrayPointer[i]);  
          }
    }
    void main()
    {
      int i;
      Function(NameList);  //Pointer To The Array Is Passed Through The Function
    }
    
    Bye the way ! in C write function declaration before main function and also specify return type for better coding practice and professional coding look.

    Enjoy....Buddy......:D
     

Share This Page