gpt4 book ai didi

c - 如何从字符数组复制到字符指针?

转载 作者:行者123 更新时间:2023-12-02 05:23:56 25 4
gpt4 key购买 nike

我正在尝试从字符数组复制到字符指针。
我的代码:

char str[] = "Hello World";
char *result = (char *)malloc(strlen(str)+1);
int index=0;
while(index <= strlen(str))
{
*result = str[index];
result++;
index++;
}

上面的代码不起作用,下面的代码正在运行
char str[] = "Hello World";
char *result = (char *)malloc(strlen(str)+1);
int index=0;
while(index <= strlen(str))
{
result[index] = str[index];
index++;
}

谁能解释这种行为?

最佳答案

我们简单地使用 strcpy 函数将数组复制到指针中。

     char str[] = "Hello World";
char *result = (char *)malloc(strlen(str)+1);
strcpy(result,str);

关于c - 如何从字符数组复制到字符指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28087519/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com