【问题标题】:best way to add char* prefix to existing char* in C [duplicate]将 char* 前缀添加到 C 中现有 char* 的最佳方法 [重复]
【发布时间】:2015-01-08 06:59:38
【问题描述】:

我有什么:

char * a = "world";
char * b = "Hello";

我需要的是:

char * a = "Hello World";

我需要在 a 之前添加 b。 有什么功能可以做到吗?

【问题讨论】:

标签: c arrays char


【解决方案1】:

如下图即可轻松完成:

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

main()
{
char * a = "world";
char * b = "Hello";
char *c = malloc(strlen(a)+strlen(b)+1);
strcpy(c,b);
strcat(c,a);
printf("%s\n",c);
free(c);
}

【讨论】:

  • 添加到这个答案的几个建议:以 strlen(a) + strlen(b) + 1 作为大小,而不是将其硬编码为 20,并记住检查 malloc 失败以避免 GPF /段错误。
  • @Chris 刚刚展示了它是如何完成的,但同意你的观点,硬编码绝不是一个好主意
  • 完全理解,无论如何都不会推断出任何负面的东西 :) 如果可以的话,我喜欢利用这些类型的问题向新开发人员展示这些考虑因素。未来的好技能等等。干杯。
【解决方案2】:

您可以使用strcat(3)snprintf(3)asprintf(3)

使用strcat,您需要检查buffer overflow(使用strlen(3)...) 使用strcat & snprintf,您需要预先分配数组。 使用asprintf,您将获得一个堆分配的缓冲区,您需要适当地free

所以,使用strcat 和一个固定大小的缓冲区buf

char buf[64];
if (strlen(a)+strlen(b)<sizeof(buf)) {
  strcpy(buf, a);
  strcat(buf, b);
}
// now buf contains "worldhello"

或者,您可以使用堆分配的缓冲区:
char*buf = malloc(strlen(a)+strlen(b)+1);,但不要忘记检查 malloc 失败:if (!buf) { perror("malloc buf"); exit(EXIT_FAILURE); };,然后像以前一样执行 strcpystrcat。当然,您需要稍后在适当的时候free(buf)。请注意,您可以先保留int lena=strlen(a);,然后再保留strcpy(buf+lena,b),而不是调用strcat


使用snprintf 和固定大小的缓冲区buf(无需检查缓冲区溢出,因为snprintf 已指定缓冲区大小):

char buf[54];
int len= snprintf(buf, sizeof(buf), "%s%s", a, b);
// now buf contains "worldhello" and len contains the required length

snprintf 的好处在于它可以理解 printf 格式控制字符串(例如,%d 用于十进制整数,%g 用于科学记数法中的浮点等...)


使用asprintf(在提供它的 Linux 等系统上)

char* buf = asprintf("%s%s", a, b);

但您需要在适当的时候致电free(buf) 以避免memory leak

另请参阅strdup(3)fmemopen(3)open_memstream

在您的问题中,您应该交换 ab

【讨论】:

    猜你喜欢
    • 2013-06-11
    • 2023-03-13
    • 1970-01-01
    • 2010-12-16
    • 1970-01-01
    • 2013-01-25
    • 2013-08-20
    • 1970-01-01
    • 2012-10-08
    相关资源
    最近更新 更多