Total members 10249 | Gratitudes |It is currently Thu May 17, 2012 7:43 am Login / Join Codemiles


All times are UTC [ DST ]




Post new topic Reply to topic  Quick reply  [ 2 posts ] 
Author Question
 Question subject: C++ array copying
PostPosted: Fri Nov 07, 2008 6:12 pm 
Offline
Proficient
User avatar

Joined: Sun Oct 19, 2008 3:47 pm
Posts: 281
Has thanked: 0 time
Have thanks: 1 time

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:


TOP
 Profile Send private message  
Reply with quote  
 Question subject: Re: C++ array copying
PostPosted: Fri Nov 07, 2008 6:13 pm 
Offline
Proficient
User avatar

Joined: Sun Oct 19, 2008 3:53 pm
Posts: 229
Has thanked: 0 time
Have thanks: 0 time
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:

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.


TOP
 Profile Send private message  
Reply with quote  
Post new topic Reply to topic Quick reply  [ 2 posts ] 
Quick reply


  

 Similar topics
 search for string in a cell array
 Shuffle Array
 check array contains a value using javascript
 Array size to zero
 array in oracle database
 How to write C++ code that defines array of size 24 then;
 access element in array C++
 Average of an array. Please help
 need some help with array comparing program (solved)
 PHP SOAP server returns array using NuSOAP Library

All times are UTC [ DST ]


Users browsing similar posts

Users browsing this forum: No registered users and 1 guest



Jump to:  
Previous Question | Next Question 




Home
General Talks
Finished Projects
Code Library
Games
Tutorials

Java
C/C++
C-sharp
php
Script
JSP/Servlets
Ajax
ASP/ASP.net
Google SEO
Database
Communications
Phpbb3 styles
Photoshop tutorials
Flash tutorials
Find a job






Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group
All copyrights reserved to codemiles.com 2007-2011
mileX v1.0 designed by codemiles team