我想在现有的字符串中分配内存,但仍想将存储的数据保存在该字符串中
#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/