使用 char 指针和 strcat 函数

6
我想使用两个字符指针打印出"Hello - World",但是我遇到了"Segmentation fault (core dumped)"的问题。
#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;
}

1
尝试使用char x[20]代替char* x - Blaze
2个回答

3

你实际上想将一个字符串字面量用作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;
}

0

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接