【问题标题】:Use strcat function with char pointer [duplicate]使用带有char指针的strcat函数[重复]
【发布时间】:2019-09-19 06:05:41
【问题描述】:
我想使用两个字符指针打印“Hello - World”,但我
有“分段错误(核心转储)”问题。
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#define Hyphen " - "
int main()
{
char* x="Hello";
char* y="'World'";
strcat(x, Hyphen);
strcat(x, y);
printf("%s",x);
return 0;
}
【问题讨论】:
标签:
c
pointers
string-literals
strcat
【解决方案1】:
您实际上是在尝试使用字符串文字作为strcat() 的目标缓冲区。这是UB,有两个原因
- 您正在尝试修改字符串文字。
- 您正在尝试写入超出分配的内存。
解决方案:您需要定义一个数组,其长度足以容纳连接的字符串,并将其用作目标缓冲区。
通过更改代码的一个示例解决方案:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#define Hyphen " - "
#define ARR_SIZE 32 // define a constant as array dimention
int main(void) //correct signature
{
char x[ARR_SIZE]="Hello"; //define an array, and initialize with "Hello"
char* y="'World'";
strcat(x, Hyphen); // the destination has enough space
strcat(x, y); // now also the destination has enough space
printf("%s",x); // no problem.
return 0;
}
【解决方案2】:
字符串文字在 C(和 C++)中是不可变的。
要将一个字符串连接到另一个字符串,最后一个字符串(即字符数组)应有足够的空间容纳第一个字符串。
许多使用指针的解决方案是为(结果)字符数组动态分配足够的内存,然后连接字符数组中的字符串。
例如
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#define Hyphen " - "
int main( void )
{
const char *x = "Hello";
const char *y = "'World'";
size_t n = strlen( x ) + strlen( y ) + strlen( Hyphen ) + 1;
char *s = malloc( n );
strcpy( s, x );
strcat( s, Hyphen );
strcat( s, y );
puts( s );
free( s );
return 0;
}
程序输出是
Hello - 'World'
如果您想排除字符串 "'World'" 周围的单引号,那么代码可以如下所示。
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#define Hyphen " - "
int main( void )
{
const char *x = "Hello";
const char *y = "'World'";
size_t n = strlen( x ) + ( strlen( y ) - 2 ) + strlen( Hyphen ) + 2;
char *s = malloc( n );
strcpy( s, x );
strcat( s, Hyphen );
strcat( s, y + 1 );
s[strlen( s ) - 1] = '\0';
// or
// s[n - 2] = '\0';
puts( s );
free( s );
return 0;
}