Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing char array by reference

I am passing a char array by reference but when I return from function and print the array, it displays nothing. What am I doing wrong?

#include <iostream>

using namespace std;

void func(char []);
int main()
{
   char a[100];
   func(a);

   cout << a<<endl;
   return 0;
}

void func(char *array)
{
   array="Inserting data in array a";
   cout << array<<endl;
}

Regards

like image 252
Naruto Avatar asked Oct 20 '12 11:10

Naruto


People also ask

How do you pass a char array as a reference?

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.

Can you pass arrays by reference?

Arrays can be passed by reference OR by degrading to a pointer. For example, using char arr[1]; foo(char arr[]). , arr degrades to a pointer; while using char arr[1]; foo(char (&arr)[1]) , arr is passed as a reference. It's notable that the former form is often regarded as ill-formed since the dimension is lost.

Is array passed by reference in C++?

Passing arrays to functions in C/C++ are passed by reference. Even though we do not create a reference variable, the compiler passes the pointer to the array, making the original array available for the called function's use. Thus, if the function modifies the array, it will be reflected back to the original array.

How do you pass a char array to a function in C++?

A whole array cannot be passed as an argument to a function in C++. You can, however, pass a pointer to an array without an index by specifying the array's name. In C, when we pass an array to a function say fun(), it is always treated as a pointer by fun(). The below example demonstrates the same.


1 Answers

What you can probably do is:

void func( char (& array)[10] ) {

}

Which translates to: pass an array ([..]) of 10 ( [10] ) characters ( char ) by reference ( (& ..) ).

like image 78
David G Avatar answered Sep 17 '22 23:09

David G