将一个数组中的值存放到另一个数组 c++

如题所述

#include<stdio.h>
#include<string.h>
void copy(char *p,char*p1,int x=0);//字符串数组 ,x拷贝的起始位置
//整型数组
void copy2(int a[], int b[],int anum,int bnum); //anum是数组a的大小,bnum是数组b的大小, a是源数组,b是从a中拷贝的数组
int main(void)
{
//字符串数组
char p[100],p1[40];
int m; printf("输入字符数组:");
gets(p);
printf("输入你要copy的位置:");
scanf("%d",&m);
if(strlen(p)<m)
printf("error\n");
else{
copy(p,p1,m);
printf("%s\n",p1);
}
int a[10]={1,2,3,4,5,6,7,8,9,0};
int b[10]={};
copy2(a,b,10,10);
printf("输出拷贝的整数值:\n");
for (int i=0; i<10; i++)
{
printf("%d",b[i]);
}
printf("\n");
return 0;
}
void copy(char*p,char*p1,int x)
{
int n=0;
while(n<x-1)
{
n++;//控制变量!
p++;
}
char * temp = p1; //temp指向p1字符串,用temp做字符串移动指针,为字符变量赋值
while(*p)
{
*temp=*p;
temp++;
p++;
}
*temp='\0';
printf("%s\n",p1); //之前p1不能输出,是因为p1指向的地址值是字符串的末尾,所以输出为空
//现在用temp做移动指针,p1的值还是指向字符串的首地址,所以可以输出字符串了
}
void copy2(int a[], int b[],int anum,int bnum)
{
//判断,取长度小的值作为循环判断条件
int temp=0;
if (anum > bnum)
{
temp = bnum;
}
else
{
temp = anum;
}
for(int i=0; i<temp; i++)
{
b[i]=a[i];
}
}

有两种,一是字符串拷贝(x值可设置拷贝的起点),二是整型数组拷贝
希望对你有帮助!!!
温馨提示:答案为网友推荐,仅供参考

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网