简体   繁体   English

C - 用指针连接字符串

[英]C - string concatenation with pointers

why does the following string concatenation does not work?为什么以下字符串连接不起作用?

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

}

I got this problem in exercise questions in one of a book on pointers.我在一本关于指针的书中的练习题中遇到了这个问题。 The question mentions问题提到

[Q] Is the code correct if not why and also correct the code. [Q] 代码是否正确(如果不正确),并更正代码。

See my answer to the question concatenation of character arrays in c请参阅我对c 中字符数组的串联问题的回答

You may not change string literals.您不能更改字符串文字。

This statement这个说法

str3 = strcat(str1, str2 ) ;

tries to change the string literal str1 and moreover tries to write beyond the string literal.尝试更改字符串文字str1并且尝试写入超出字符串文字的内容。

To make a concatenated string you have to allocate a memory large enough to contain the both strings.要制作连接字符串,您必须分配足够大的内存以包含两个字符串。

What you need is the following您需要的是以下内容

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

The program output is程序输出是

UnitedFront

When you write char* s = "something" a piece of read-only memory is allocated.当您编写char* s = "something" ,会分配一块只读内存。 More on this here .更多关于这里

The declaration of strcat looks like this: strcat的声明如下所示:

char *strcat( char *dest, const char *src );

Basically what it will do is append src to dest , but since your destination, str1 does not have enough memory to hold both strings.基本上它会做的是将src附加到dest ,但是由于您的目的地, str1没有足够的内存来保存两个字符串。

So what I would do is, either use snprintf with a pre-allocated buffer or:所以我要做的是,使用带有预分配缓冲区的snprintf或:

char *str1 = "United";
char *str2 = "Front";

char *buf = calloc(strlen(str1) + strlen(str2) + 1, sizeof(char));

strncpy(buf, str1, strlen(str1));
strncat(buf, str2, strlen(str2));

printf("%s", buf);

Or with snprintf :或使用snprintf

char *str1 = "United";
char *str2 = "Front";

int buf_len = strlen(str1) + strlen(str2) + 1;
char *buf = calloc(buf_len, sizeof(char));

snprintf(buf, buf_len, "%s%s", str1, str2);

The first parameter of strcat ( str1 in your case) needs to have enough allocated memory to hold the concatenated string. strcat的第一个参数(在你的例子中是str1 )需要有足够的分配内存来保存连接的字符串。 You can either create it with malloc or declare it as an array with a big enough size.您可以使用malloc创建它,也可以将其声明为一个足够大的数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM