帮忙改正一下错误.

来源:百度知道 编辑:UC知道 时间:2024/06/06 10:34:16
copy_app为复制函数,将source里的内容复制到target里,函数内部使用的指针.

源代码如下:
#include <stdio.h>
#include <stdlib.h>
void copy_app(int *x,int *y,int n);

int main(void)
{
int source[5] = {1,2,3,4,5};
int target[5] = {0};

copy_app(source,target,5);

system("pause");
return 0;
}

void copy_app(int *x,int *y,int n)
{
int i;

for(i=0;i<n;i++)
*y++=*x++;

for(i=0;i<n;i++)
printf("%d ",*y++);
}

输出有点问题,,,我输出的是
-858993460 -858993460 1 2 3

谢谢各位前辈了,

#include <stdio.h>
#include <stdlib.h>
void copy_app(int *x,int *y,int n);

int main(void)
{
int source[5] = {1,2,3,4,5};
int target[5] = {0};

copy_app(source,target,5);

system("pause");
return 0;
}

void copy_app(int *x,int *y,int n)
{
int i;

for(i=0;i<n;i++)
*y++=*x++;

//for(i=0;i<n;i++) //////////错误在这里。因为,执行过上面的for循环赋值,y已经不指向target的首地址了,再继续y++下去,输出的是什么都不知道了
//printf("%d ",*y++); ///////可以在函数外部,去打印输出target,这也符合本函数的功能设计,因为本函数是copy数据,不应该去完成其他的功能
}

这样改吧:
#include <stdio.h>
#include <stdlib.h>
void copy_app(int *x,int *y,int n);

int main(void)
{
int source[5] = {1,2,3,4,5};
int target[5] = {0};
int i;

copy_app(source,target,5);

for(i=0;i<n;i++)
printf("%d ",target[i]);

system(&quo