一共有四种情况使用memcpy,对于使用&还是不适用什么时候使用一直很困惑,虽然现在仍未全部清除,不过初步已经了解一些。果然还是对指针不熟悉,否则会理解的更好。
- 使用memcpy 拷贝数组
int res2[5] = { 0 };int res2_dest[5] = { 1, 1,1,1,1 };for (int i = 0; i < 5; i++){cout << res2_dest[i] << endl;}memcpy(res2_dest, res2, 5 * sizeof(int));for (int i = 0; i < 5; i++){cout << res2_dest[i] << endl;}
- 使用memcpy 拷贝指针数组
注:对于指针数组,需要是 地址符。可以将整个指针数组copy到目标指针数组,也可以一个一个循环copy。
int * res = new int[5];for (int i = 0; i < 5; i++){res[i] = i;}int * res_dest = new int[5];memcpy(&res_dest, &res, 5 * sizeof(int));for (int i = 0; i < 5; i++){cout << res_dest[i] << endl;}for (int i = 0; i < 5; i++){res[i] = 0;memcpy(&res_dest[i], &res[i], sizeof(int));}for (int i = 0; i < 5; i++){cout << res_dest[i] << endl;}
- 将一个指针数组copy到二维数组中
//将一个数组copy到二维数组中float * src3 = new float[5];for (int i = 0; i < 5; i++){src3[i] = i;}float ** dest3 = new float*[3];for (int i = 0; i < 3; i++){dest3[i] = new float[4];for (int j = 0; j < 4; j++){dest3[i][j] = j;}}for (int i = 0; i < 3; i++){memcpy(dest3[i], src3, sizeof(float) * 5); //注意这里是src3, dest3[i]}for (int i = 0; i < 3; i++){for (int j = 0; j < 4; j++){cout << dest3[i][j] << endl;}}
输出结果:
0
1
2
3
0
1
2
3
0
1
2
3
- 将一个二维数组copy到另一个二维数组中
//将一个二维数组copy到另一个二维数组中float ** src4 = new float*[2];for (int i = 0; i < 2; i++){src4[i] = new float[4];for (int j = 0; j < 4; j++){src4[i][j] = j + 100;}}float ** dest4 = new float*[2];for (int i = 0; i < 2; i++){dest4[i] = new float[4];for (int j = 0; j < 4; j++){dest4[i][j] = j;}}for (int i = 0; i < 2; i++){memcpy(dest4[i], src4[i], sizeof(float) * 4);//注意这里是src4[i], dest4[i]}for (int i = 0; i < 2; i++){for (int j = 0; j < 4; j++){cout << dest4[i][j] << endl;}}
输出结果:
100
101
102
103
100
101
102
103