gpt4 book ai didi

在 C 中链接 2 个字符串

转载 作者:行者123 更新时间:2023-11-30 14:48:56 24 4
gpt4 key购买 nike

我想在 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;

}

最佳答案

您的代码中存在多个问题:

  • malloc 版本中,为目标字符串分配的空间被硬编码为 15,而不是计算为 lengh1 + lengh2 + 1,有足够的空间容纳字符串和尾随空字节。
  • 您没有在两个版本中的目标字符串末尾设置空终止符。
  • 在没有 malloc 的版本中,您必须提供足够大的数组作为 concat() 的目标。字符串常量无法修改。一个简单的解决方案是将目标缓冲区和源字符串作为单独的参数传递。

以下是修改后的版本:

char *concat(const char *s1, const char *s2) {
int length1 = simple_strlen(s1);
int length2 = simple_strlen(s2);
char *result = malloc(length1 + length2 + 1);
int i, j;
for (i = 0; i < length1; i++) {
result[i] = s1[i];
}
for (i = 0; i < length2; i++) {
result[length1 + i] = s2[1];
}
result[length1 + length2] = '\0';
return result;
}

没有malloc():

#include <string.h>

char *concat(char *dest, const char *s1, const char *s2) {
char *p = dest;
while (*s1)
*p++ = *s1++;
while (*s2)
*p++ = *s2++;
*p = '\0';
return dest;
}

int main() {
char buf[100];
/* output expected "helloworld" */
printf("%s\n", concat(buf, "hello", "world"));
return 0;
}

关于在 C 中链接 2 个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50104878/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com