Switch to full style
For C/C++ coders discussions and solutions
Post a reply

C++ array copying

Fri Nov 07, 2008 6:12 pm

Code:
1: #include <iostream>
2:
3: int main()
4: {
5: short age[4];
6: short same_age[4];
7: age[0]=23;
8: age[1]=34;
9: age[2]=65;
10: age[3]=74;
11:
12: same_age=age; --> Array copying
13:
14: std::cout << same_age[0] << std::endl;
15: std::cout << same_age[1] << std::endl;
16: std::cout << same_age[2] << std::endl;
17: std::cout << same_age[3] << std::endl;
18: return 0;
19: }



Array copying is done in line number 12. Is this allowed in C++? I did
googling, got few answers saying "No". :grin:



Re: C++ array copying

Fri Nov 07, 2008 6:13 pm

Arrays can be copied but only by copying their individual
elements. E.g. you can use the library function strcpy() to
copy strings (arrays of char).

Because of the close link between array names and pointers,
assigning an array name does not copy the underlying array,
but instead makes the pointer an alias for the array name:

Code:
int i;
int a[] = {1, 2, 3};
int *b = a;


Now a[i] and b[i] refer to the same area of memory. The
array values themselves have not been copied. Changing b[i]
will change a[i] and vice versa, because they're the same
thing.

If you want to copy an array, as John Matthews suggests, you
can wrap it in a struct. Structs can be copied and can even
be returned by functions.

Post a reply
  Related Posts  to : C++ array copying
 Array difference for associate array     -  
 compare an array with another array?     -  
 Shuffle Array     -  
 Pop the element off the end of array     -  
 Here is how to display any 2d array     -  
 PHP Array Functions     -  
 Array Passing     -  
 Array shuffle     -  
 Average of an array. Please help     -  
 Imploding an Array     -  

Topic Tags

C++ Arrays