Passing Pointer-To-An-Array Through Function

tppramod's Avatar, Join Date: Jan 2009
Newbie Member
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 shabbir; 1Jan2009 at 20:52.. Reason: Code Block
0
Jadav Rakesh C.'s Avatar, Join Date: Nov 2007
Go4Expert Member
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......