C++:复制数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3598859/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 13:14:20  来源:igfitidea点击:

C++: copy array

c++

提问by Hyman moore

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

是否可以在 C++ 中做这样的事情(现在不能自己测试)?

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++.

我可以在 JavaScript 中做这样的事情,但就像我说的 - 不要认为在 C++ 中这是可能的。

Thanks for your time.

谢谢你的时间。

回答by TonyK

#include <cstring>

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

回答by Puppy

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.

然而,C++ 与 Javascript 是如此不同,说真的,只是不要打扰。如果您需要编写 C++ 代码,请获取实际的 C++ 资源并学习它。基本内容的语法是唯一的共同点。

回答by Kamil Klimek

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. (I.E. in pointer array put NULL pointer at end of array)

这两种情况都是不可能的。您必须将数组长度作为参数(了解它),或者将某种“终止符”作为最后一个元素放入数组中。(指针数组中的 IE 将 NULL 指针放在数组末尾)