[英]C - Copy contents of one char array to another using pointers
I'm trying to write a simple C function to copy the contents of one char array to another using pointer arithmetic. 我正在尝试编写一个简单的C函数,使用指针算法将一个char数组的内容复制到另一个char数组。 I can't seem to get it working, can you tell me where I'm going wrong?
我似乎无法让它工作,你能告诉我哪里出错了吗?
#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
}
Help appreciated, thanks. 帮助表示感谢,谢谢。
EDIT: Here is the working code: 编辑:这是工作代码:
#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++;
}
}
You are only copying the first character of the string. 您只是复制字符串的第一个字符。
void copystring(char* str1, const char* str2)
{
while(*str2)
{
*str1 = *str2; //copy value of *str2 into *str1
str1++;
str2++;
}
}
and then in main, after calling copystring 然后在main中调用copystring之后
printf("%s %s", hello, world); //print "world" twice
But please don't do this! 但请不要这样做! Use strncpy in real life, if working with plain C strings.
如果使用普通的C字符串,请在现实生活中使用strncpy 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.