c - 为字符串分配内存以写入更多数据

标签 c malloc

我想在现有的字符串中分配内存,但仍想将存储的数据保存在该字符串中

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

main()
{
char *str1= "hello";
char *str2= "Abhimanyu";

char *str = malloc( strlen(str1) + strlen(str2) +1 );

strcpy(str,str1);
strcat(str,str2);
printf("%s",str);
return 0;
}

我想要的是在现有的 str1 中使用 malloc 分配一些而不使用 str 是否可能?

最佳答案

我看到的唯一方法如下

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

#define HELLO "hello"

int main( void )
{
   char *str2 = "Abhimanyu";
   char *str1 = malloc( sizeof( HELLO ) );

   strcpy( str1, HELLO );

   str1 = realloc( str1, strlen( str1 ) + strlen( str2 ) +1 );
   strcat( str1, str2 );

   printf( "%s\n", str1 );

   free( str1 );

   return 0;
}

关于c - 为字符串分配内存以写入更多数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24875959/

相关文章:

c - scanf 跳过所有直到一个字符串

C套接字编程,发送

c++ - 使用 malloc 和 realloc 的最佳方式

C - 指针的正确语法

c - 我如何获得此readdir代码示例以搜索其他目录

c++ - include <name.h> 和 libname.o 处的库名称之间的链接

c - 解释 void (*signal(int signo, void *(func)(int)))(int)

c - 指向结构数组的指针

c - C 中的内存分配,堆中的链接列表

Git 克隆因内存不足错误而失败 - "fatal: out of memory, malloc failed (tried to allocate 905574791 bytes)/fatal: index-pack failed"