Pass By Reference - Char Array

Hey Guys,

From the coding, how can I pass a word instead of a character only?

#include <iostream>
using namespace std;

void print(char &);

void print(char &array)
{ cout<<array<<endl; }

int main()
{
char array[5]={'a'};

print(array[0]);

return 0;
}

Looking forward for the guidance. Thank You =)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
using namespace std;

void print(char* array)
{ cout<<array<<endl; }

int main()
{

char array[5]={'a', 'b', 'c', 'd', 0};
print(array);

return 0;
} 
Last edited on
Why don't you just use std::string ?
There are two ways. The first is to declare the parameter as a pointer to a const string. The second is to declare the parameter as a reference to an array.
Also ypu can write a template function.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>

using namespace std;
 
void print1( const char *s )
{ 
   cout << s << endl; 
}
 
void print2( const char ( &s )[5] )
{ 
   cout << s << endl; 
}
 
template <size_t N = 5>
void print3( const char ( &s )[N] )
{ 
   cout << s << endl; 
}

int main()
{
   char array[5] = { 'a' };
 
   print1( array );
   print2( array );
   print3<>( array );
 
   return 0;
} 
Thanks for the Respond guys, really appreciate it.

How could I only print one of the value? For example, I have a-d and I only want to print c?

Thanks =)
Topic archived. No new replies allowed.