将一个数组分配给另一个数组C ++ [英] Assigning one array to another array c++

查看:106
本文介绍了将一个数组分配给另一个数组C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,我是c ++的初学者,有人可以向我解释一下

Hello I am beginner in c++ , can someone explain to me this

char a[]="Hello";

char b[]=a; // is not legal 

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);

推荐答案

它不是在复制数组.它把它变成一个指针.修改后,您将看到:

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

如果需要复制数组,请使用 std::copy :

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));

如果发现自己这样做,则可能要使用 std::array .

If you find yourself doing that, you might want to use an std::array.

这篇关于将一个数组分配给另一个数组C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆