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

标签 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
    }

感谢帮助,谢谢。

编辑: 这是工作代码:

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

最佳答案

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

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

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

关于C - 使用指针将一个字符数组的内容复制到另一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47103108/

相关文章:

c - 如何在C中将字符串格式化为排队格式?

javascript - 每次调用我的函数时,我都想打印 Next Day 的名称

arrays - $firebaseArray 中的 For 循环

c++ - 通过重新解释转换将 constexpr 值转换为指针

c++ - 为什么不能同时定义两个指针?

c - 不确定用字符串数组初始化一维字符数组

c - 如何使用cmake正确地将libgit2链接到C程序?

c++ - 在 C++ 类中初始化数组和可修改的左值问题

c - 在 C 中记录不同的数据类型

c++ - 为什么对固定时间步长的游戏循环使用积分? (Gaffer 谈游戏)