gpt4 book ai didi

将指针字符串复制到其他指针

转载 作者:太空宇宙 更新时间:2023-11-04 03:43:01 24 4
gpt4 key购买 nike

亲们, 我对指针有基本和简单的问题。下面是给出段错误的代码。

int main()

{

char *str = "hello, world\n";

char *strc = "good morning\n";

strcpy(strc, str);

printf("%s\n", strc);

return 0;

}

我们不能从指针复制到其他指针吗?

  1. 如果我有 char *strc = "good morning\n",我不能这样做吗strc[5] = '.';.为什么这也会出现段错误。

最佳答案

您不能更改字符串文字。这是你在声明中试图做的事情

strcpy(strc, str);

那是你试图覆盖指针 strc 指向的字符串文字“good morning\n”。

当然,您可以在函数 strcpy 中使用指针。有效代码看起来像

#include <stdio.h>
#include <string.h>

int main()
{
char *str = "hello, world\n";

char strc[] = "good morning\n";

strcpy(strc, str);

printf("%s\n", strc);

return 0;
}

或者

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main()
{
char *str = "hello, world\n";

char *strc = malloc( 14 * sizeof( char ) );
strcpy( strc, "good morning\n" );

//...

strcpy(strc, str);

printf("%s\n", strc);

free( strc );

return 0;
}

关于将指针字符串复制到其他指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27025812/

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