som*_*ers 5 c arrays pointers char
我正在尝试编写一个简单的 C 函数来使用指针算法将一个 char 数组的内容复制到另一个。我似乎无法让它工作,你能告诉我哪里出错了吗?
#include <stdio.h>
#include <stdlib.h>
void copystr(char *, const char *);
int main()
{
char hello[6] = "hello";
const char world[6] = "world";
copystr(&hello, &world);
return 0;
}
void copystr(char *str1, const char *str2)
{
*str1 = *str2; //copy value of *str2 into *str1
printf("%s %s", *str1, *str2); //print "world" twice
}
Run Code Online (Sandbox Code Playgroud)
帮助表示赞赏,谢谢。
编辑:这是工作代码:
#include <stdio.h>
#include <stdlib.h>
void copystr(char *, const char *);
int main()
{
char hello[6] = "hello";
const char world[6] = "world";
copystr(hello, world);
printf("%s %s", hello, world);
return 0;
}
void copystr(char *str1, const char *str2)
{
/*copy value of *str2 into *str1 character by character*/
while(*str2)
{
*str1 = *str2;
str1++;
str2++;
}
}
Run Code Online (Sandbox Code Playgroud)
您仅复制字符串的第一个字符。
void copystring(char* str1, const char* str2)
{
while(*str2)
{
*str1 = *str2; //copy value of *str2 into *str1
str1++;
str2++;
}
}
Run Code Online (Sandbox Code Playgroud)
然后在 main 中,调用 copystring 之后
printf("%s %s", hello, world); //print "world" twice
Run Code Online (Sandbox Code Playgroud)
但请不要这样做!如果使用纯 C 字符串,请在现实生活中使用strncpy 。