我正在使用以下代码将字符串内容复制到另一个字符串。 使用了两种逻辑,一种使用 while 循环(注释)有效,另一种不使用(as=at)。
请帮我找出这段代码中的缺陷。
提前致谢
#include<stdio.h>
#include<conio.h>
main()
{
char *s="SourceString";
char *t="TargetString";
void print(char *s);
void strcopy(char *s,const char *t);
print(s);
strcopy(s,t);
print(s);
getch();
}
void strcopy(char *as,const char *at)
{
/*while((*as=*at)!='\0') // working
{
as++;
at++;
} */
as=at; //not working
}
void print(char *s)
{
printf("\n Printing the Contents:");
for(;*s!='\0';s++)
printf("%c",*s);
printf("\n END");
}
所有人都说字符串是按值而不是地址传递的。 但是我在调用函数中传递字符串的地址,而在被调用函数中我使用指针。 请说明我是指针的新手
最佳答案
当 as
是函数参数时,编写 as=anything;
在函数终止时不再有效,因为它的参数不复存在(以及它的本地变量)。您不是在修改字符串,您只是在修改一个内存单元,该内存单元临时包含字符串的地址,并且无论如何都会被释放。
你的问题其实是关于指针的问题。或许您可以在 StackOverflow 上找到一个关于 C 或 C++ 中的指针的已问问题,这对您有帮助。
关于c - strcpy 示例程序中的缺陷,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2298631/