简体   繁体   中英

C++: copy array

Is it possible to do something like this in C++ (can't test it myself right now)?

int myarray[10] = {111,222,333,444,555,666,777,888,999,1234};

void functioncc()
{
 int temparray = myarray;
 for(int x=0; x<temparray.length; x++){
    .... do something
 }

}

And maybe this (but i dont think it is):

int array1[5] = {0,1,2,3,4,5,6,7,8,9};
int array2[5] = {9,8,7,6,5,4,3,2,1,0};

void functioncc(int arid)
{
  temparray[10] = "array"+arid;
  ........

}

I can do stuff like that in JavaScript, but like I said - don't think it would be possible in C++.

Thanks for your time.

#include <cstring>

int temparray[10] ;
memcpy (temparray, myarray, sizeof (myarray)) ;

Sure.

int myarray[] = {111,222,333,444,555,666,777,888,999,1234};

void function() {
    std::vector<int> temparray(std::begin(myarray), std::end(myarray));
}

Do note that the use of static non-const variables in this way is really looked down on, and if you pass them to other functions, you will have to also pass the "end" pointer.

However, C++ is so distinct from Javascript, seriously, just don't bother. If you need to code C++, get an actual C++ resource and learn it. The syntax for the basic stuff is the ONLY thing in common.

Both cases are impossible. You must either put array length as an argument (know about it), or put inside of array some kind of "terminator" as last element. (IE in pointer array put NULL pointer at end of array)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM