【发布时间】:2018-04-30 16:50:57
【问题描述】:
我想在 C 中链接 2 个字符串。我使用的函数称为 concat()
首先我定义了这样的东西并且它起作用了
char* concat(const char *s1, const char *s2)
{
char* result = malloc (15);
int lengh1 = simple_strlen (s1);
int lengh2 = simple_strlen (s2);
int i=0,j;
for ( i = 0 ;i < lengh1;i++){
if (i!=lengh1-1)
result[i]=s1[i];
else{
result[i]=s1[i];
for ( j=i+1 ; j< lengh1+lengh2;j++){
result[j] = s2[j-i-1];
}
}
}
return result;
}
但是后来我被要求在没有 malloc() 的情况下这样做,所以我定义了这样的内容:
char* concat( char *result, const char *s2)
{
int lengh1 = simple_strlen (result);
int lengh2 = simple_strlen (s2);
int i=0;
for ( i = 0 ;i < lengh2;i++){
result[i+lengh1]=s2[i];
}
return result;
}
但它有分段错误
example:
int main(int argc , char* argv[], char* envp[])
{
printf(concat( "hello", "world"));/*output expected "helloworld"*/
return 0;
}
【问题讨论】:
-
请为您的第二个示例显示minimal reproducible example。这个函数是怎么调用的?
-
我假设
result没有初始化为指向任何东西,或者它指向的地方不足以存储您的连接字符串。但我们无法确定,因为您没有提供 MCVE。 -
你需要回顾一下内存和字符串。您的第二种方法会导致错误,因为您无法在“结果”结束后使用内存。您的问题可能定义不明确,因为虽然您可以说“不要使用 malloc”,但您必须有一些地方来放置新字符串。
-
@OldProgrammer 示例已添加
-
您的“结果”字符串没有足够的额外内存来容纳“s2”字符串中的字符。
标签: c string segmentation-fault