(X)->sh_name+"new" + 在 C 中不连接字符串。它试图添加指向无效指针的指针。
你需要使用函数strcat或strncat
对不起,这些函数会影响字符串,但我想要一个新的 -
就这么简单:
char *strcatAlloc(const char * restrict s1, const char * restrict s2)
{
size_t s1len;
char *newstring;
if(s1 && s2)
{
s1len = strlen(s1);
newstring = malloc(s1len + strlen(s2) + 1);
if(newstring)
{
strcpy(newstring, s1);
strcpy(newstring + s1len, s2);
}
}
return newstring;
}
int main(void)
{
// you should check if the function fails. Omitted for the example clarity
printf("`%s`\n", strcatAlloc("hello ", "world"));
printf("`%s`\n", strcatAlloc("", "world"));
printf("`%s`\n", strcatAlloc("hello ", ""));
printf("`%s`\n", strcatAlloc("", ""));
//you should free allocated space
}
或您可以传递缓冲区的版本(如果该缓冲区为 NULL,它将分配内存)
char *strcatAlloc(const char * restrict s1, const char * restrict s2, char *buff)
{
size_t s1len;
if(s1 && s2)
{
s1len = strlen(s1);
if(!buff) buff = malloc(s1len + strlen(s2) + 1);
if(buff)
{
strcpy(buff, s1);
strcpy(buff + s1len, s2);
}
}
return buff;
}
int main(void)
{
char s[100];
// you should check if the function fails. Omitted for the example
printf("`%s`\n", strcatAlloc("hello ", "world", NULL));
printf("`%s`\n", strcatAlloc("", "world", NULL));
printf("`%s`\n", strcatAlloc("hello ", "", s)); //you can pass your own large enough buffer
printf("`%s`\n", strcatAlloc("", "", NULL));
//you should free allocaated space
}