C - 使用指针将一个char数组的内容复制到另一个char数组

时间:2017-11-03 19:22:48

标签: c arrays pointers char

我试图编写一个简单的C函数,使用指针算法将一个char数组的内容复制到另一个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
    }

帮助表示感谢,谢谢。

编辑: 这是工作代码:

#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++;
    }
}

1 个答案:

答案 0 :(得分:4)

您只是复制字符串的第一个字符。

void copystring(char* str1, const char* str2)
{
    while(*str2)
    {
        *str1 = *str2;                 //copy value of *str2 into *str1
        str1++;
        str2++;
    }
}

然后在main中,在调用copystring之后

    printf("%s %s", hello, world); //print "world" twice

但请不要这样做!如果使用普通的C字符串,请在现实生活中使用strncpy

相关问题