gpt4 book ai didi

C - 带指针的字符串连接

转载 作者:行者123 更新时间:2023-11-30 21:05:07 26 4
gpt4 key购买 nike

为什么下面的字符串连接不起作用?

main()
{
char *str1 = "United";
char *str2= "Front";
char *str3;
str3 = strcat(str1, str2 ) ;
printf("\n%s",str3 );

}

我在一本关于指针的书中的练习题中遇到了这个问题。问题提到了

[Q] Is the code correct if not why and also correct the code.

最佳答案

查看我对问题 concatenation of character arrays in c 的回答

您不得更改字符串文字。

本声明

str3 = strcat(str1, str2 ) ;

尝试更改字符串文字str1,并且尝试写入超出字符串文字的内容。

要创建一个连接字符串,您必须分配足够大的内存来容纳这两个字符串。

您需要的是以下内容

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

int main(void)
{
const char *str1 = "United";
const char *str2 = "Front";

char *str3 = malloc( strlen( str1 ) + strlen( str2 ) + 1 );

strcpy( str3, str1 );
puts( strcat( str3, str2 ) );

free( str3 );

return 0;
}

程序输出为

UnitedFront

关于C - 带指针的字符串连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56645659/

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