Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning one array to another array c++ [duplicate]

Tags:

c++

arrays

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);
like image 372
Bala Avatar asked May 24 '14 23:05

Bala


People also ask

Can I assign an array to another array in C?

You cannot assign an array (here b ) by a pointer to the first element of another array (here a ) by using b = a; in C. The syntax doesn't allow that.

How do you assign one array to another array?

Ensure that the two arrays have the same rank (number of dimensions) and compatible element data types. Use a standard assignment statement to assign the source array to the destination array. Do not follow either array name with parentheses.

What happens if we assign an array to another array of same type?

When you use the assignment statement to copy an array, the two arrays must have the same type, dimensions, and size; otherwise, an error condition will occur. You can use an assignment statement to create and initialize a dynamic array that has been declared but not yet created.


2 Answers

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.

like image 167
kirbyfan64sos Avatar answered Nov 11 '22 00:11

kirbyfan64sos


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.

like image 34
vsoftco Avatar answered Nov 11 '22 01:11

vsoftco