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);
4
  • It is pass by reference Commented May 24, 2014 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. Commented May 24, 2014 at 23:44
  • This answer is quite long, but it's well worth the read. All your questions are answered in it. Commented May 24, 2014 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 &). Commented May 25, 2014 at 0:49

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

What is the difference between an std::array and the arrays used in the example?
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.