Reference variable and pointer

Hey is the following form of passing an array to a function correct?


void fun(char *&nm)
{
cout<<nm;
}
void main()
{
clrscr();
char name[10];
cout<<"\nEnter your name";
fun(name);
getch();
}
have you tried it and did it work??
I read it somewhere and I think it works
I think what guestgulkan was asking was if you tried putting it in a program. If you had, you would have immediately seen it didn't work.

Generally in C/C++ to pass an array to a function you pass a pointer to an array. This is done with the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
void fun(char* nm)
{
  cout << nm;
}

int main()
{
  char name[10] = "test";
  fun(name);   // will print "test"

  getch();
  return 0;
}


Note that since you're passing the char array by-reference (via a pointer), changes you make to 'nm' in the fun() function will change the 'name' array in main().

If you don't want fun() to be able to change the source data (or if there's no need to), it's best to make it a const pointer:

1
2
3
4
void fun(const char* nm)
{
  cout << nm;
}
Thanks Disch.
Topic archived. No new replies allowed.