Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   Passing Pointer-To-An-Array Through Function (http://www.go4expert.com/forums/passing-pointer-array-function-t15699/)

tppramod 1Jan2009 20:33

Passing Pointer-To-An-Array Through Function
 
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?
      }
  }


Jadav Rakesh C. 2Jan2009 10:19

Re: Passing Pointer-To-An-Array Through Function
 
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


All times are GMT +5.5. The time now is 05:42.