24

Hello I am beginner in c++ , can someone explain to me this

char a[]="Hello";

char b[]=a; // is not legal 

whereas,

char a[]="Hello";

char* b=a; // is legal 

If a array cannot be copied or assigned to another array , why is it so that it is possible to be passed as a parameter , where a copy of the value passed is always made in the method

void copy(char[] a){....}

char[] a="Hello";

copy(a);
Mgetz
  • 5,108
  • 2
  • 33
  • 51
Bala
  • 379
  • 1
  • 2
  • 6
  • It is `pass by reference` – Ahmed Hamdy May 24 '14 at 23:38
  • 1
    The weird rules about arrays are inherited from 1970's C programming and nobody has ever changed them because too much existing code would break. Instead, you are discourage from using arrays in C++; instead use `std::vector` which has the behaviour that arrays do in most high-level languages. – M.M May 24 '14 at 23:44
  • [This answer](https://stackoverflow.com/questions/4810664/how-do-i-use-arrays-in-c?rq=1) is quite long, but it's well worth the read. All your questions are answered in it. – Praetorian May 24 '14 at 23:44
  • 2
    @AhmedHamdy, That's not pass by reference. The array decays to a pointer, which is **copied** into the function's parameter, which itself is equivalent to having a parameter `char *a`. Calling this pass by reference conflicts with actually passing by reference, via the parameter *being* a reference (i.e. it has the `&`). – chris May 25 '14 at 00:49

2 Answers2

18

It isn't copying the array; it's turning it to a pointer. If you modify it, you'll see for yourself:

void f(int x[]) { x[0]=7; }
...
int tst[] = {1,2,3};
f(tst); // tst[0] now equals 7

If you need to copy an array, use std::copy:

int a1[] = {1,2,3};
int a2[3];
std::copy(std::begin(a1), std::end(a1), std::begin(a2));

If you find yourself doing that, you might want to use an std::array.

kirbyfan64sos
  • 10,377
  • 6
  • 54
  • 75
8

The array is silently (implicitly) converted to a pointer in the function declaration, and the pointer is copied. Of course the copied pointer points to the same location as the original, so you can modify the data in the original array via the copied pointer in your function.

vsoftco
  • 55,410
  • 12
  • 139
  • 252