ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

指针练习 - 数组元素的拷贝(多种方法实现)

2022-02-01 23:03:52  阅读:192  来源: 互联网

标签:start ++ double source 数组 拷贝 copy 指针


  • 编写一个程序,初始化一个double类型的数组,然后把该数组的内容拷贝至3个其他数组中(在 main()中声明这4个数组)。
  • 第1个函数使用带数组表示法的函数进行第1份拷贝。
  • 第2个函数使用带指针表示法和指针递增的函数进行第2份拷贝。 把目标数组名、源数组名和待拷贝的元素个数作为前两个函数的参数。
  • 第3个函数以目标数组名、源数组名和指向源数组最后一个元素后面的元素的指针。
  • 也就是说,给定以下声明,则函数调用如下所示:
    double source[5] = {1.1, 2.2, 3.3, 4.4, 5.5};
    double target1[5];
    double target2[5];
    double target3[5];
    copy_arr(target1, source, 5);
    copy_ptr(target2, source, 5);
    copy_ptrs(target3, source, source + 5)
#include <iostream>
#include <Windows.h>
#include <string.h>

using namespace std;

//方式一, 使用数组传值
void copy_arr(double target1[], double source[], int len) {
	for (int i = 0; i < len; i++) {
		target1[i] = source[i];
	}
}

//方式二, 使用指针自增
void copy_ptr(double *target2, double *source, int len) {
	for (int i = 0; i < len; i++) {
		*(target2 ++) = *(source + i);
	}
}

//方式三, 使用指针指向开始, 结束作为条件
//target3:目标数组, source_start:数组起始, source_end:数组尾部
void copy_ptrs(double *target3, double *source_start, double *source_end) {
	/*for (; source_start < source_end; source_start++) {
		*(target3++) = *source_start;
	}*/
	while (source_start < source_end) {
		*(target3++) = *(source_start++);
	}
}

int main(void) {
	double source[5] = { 1.1, 2.2, 3.3, 4.4, 5.5 };
	int len = sizeof(source) / sizeof(source[0]);		//数组长度

	//把source数组的数据, 用不同的方式拷贝到以下三个数组中
	double target1[5];
	double target2[5];
	double target3[5];

	//方式一, 使用数组
	copy_arr(target1, source, len);
	cout << "target1: ";
	for (int i = 0; i < len; i++) {
		cout << target1[i] <<" ";
	}
	cout << endl;

	//方式二, 使用指针
	cout << "target2: ";
	copy_ptr(target2, source, len);
	for (int i = 0; i < len; i++) {
		cout << *(target2+i) << " ";
	}
	cout << endl;

	//方式三, 使用指针指向开始, 结束作为条件
	cout << "target3: ";
	copy_ptrs(target3, source, source + len);
	for (int i = 0; i < len; i++) {
		cout << *(target3 + i) << " ";
	}
	cout << endl;

	system("pause");
	return 0;
}

标签:start,++,double,source,数组,拷贝,copy,指针
来源: https://blog.csdn.net/qq_34606496/article/details/122766394

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有