使用带有char指针的strcat函数[duplicate]

问题描述 投票:1回答:2

我想通过使用两个char指针来打印“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;
}
c pointers string-literals strcat
2个回答
2
投票

您实际上是在尝试使用字符串文字作为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;
}
© www.soinside.com 2019 - 2024. All rights reserved.