三种通过数组的方式进行数组的拷贝,其本质都是通过地址传参,来实现数组的拷贝。
1、通过数组访问
这种访问数组的方式是最常见的
void copy1(double target[], double source[], int len){
for (int i = 0; i < len; ++i) {
target[i] = source[i];
}
}
int main(){
double source[5] = {1.1, 1.2, 1.3, 1.4, 1.5};
double target[5];
int len = sizeof(source) / sizeof(source[0]);
copy1(target, source, len);
cout << "target:";
for (int i = 0; i < len; ++i) {
cout << target[i] << " ";
}
cout << endl;
}
2、使用指针访问
void copy2(double *target, double *source, int len){
for (int i = 0; i < len; ++i) {
*target++ = *(source + i);
}
}
int main(){
double source[5] = {1.1, 1.2, 1.3, 1.4, 1.5};
double target[5];
int len = sizeof(source) / sizeof (source[0]);
copy2(target, source, len);
cout << "target:";
for (int i = 0; i < len; ++i) {
cout << target[i] << " ";
}
cout << endl;
}
3、通过两个指针实现
void copy3(double *target, double *sourceStart, double *sourceEnd){
for (; sourceStart < sourceEnd; sourceStart++) {
*target++ = *sourceStart;
}
}
int main(){
double source[5] = {1.1, 1.2, 1.3, 1.4, 1.5};
double target[5];
int len = sizeof(source) / sizeof (source[0]);
copy3(target3, source, source + 5);
cout << "target:";
for (int i = 0; i < len; ++i) {
cout << target[i] << " ";
}
cout << endl;
}
标签:target,int,double,len,source,复制,数组,拷贝,sizeof
From: https://blog.csdn.net/weixin_46089415/article/details/139885836