gpt4 book ai didi

在C中连接两个字符串

转载 作者:太空宇宙 更新时间:2023-11-04 05:56:28 25 4
gpt4 key购买 nike

所以我必须在 C 中编写一个函数来连接两个字符串;该函数通过连接 str1 和 str2 创建一个新字符串。该函数必须调用 malloc() 或calloc() 为新字符串分配内存。该函数返回新字符串。

在主测试函数中执行以下对 printf() 的调用之后:printf ( “%s\n”, myStrcat( “Hello”, “world!” ));屏幕上的打印输出必须是 Helloworld!

到目前为止,这是我的代码;我不太明白为什么它不起作用。它不执行任何操作...它编译并运行但不显示任何内容。

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

char *my_strcat( const char * const str1, const char * const str2);

int main()
{
printf("%s", my_strcat("Hello", "World")); // test function. Output of print statement is supposed to be HelloWorld
}

char *my_strcat( const char * const str1, const char * const str2)
{

char *temp1 = str1; // initializing a pointer to the first string
char *temp2 = str2; // initializing a pointer to the second string

// dynamically allocating memory for concatenated string = length of string 1 + length of string 2 + 1 for null indicator thing.
char *final_string = (char*)malloc (strlen(str1) + strlen(str2) + 1);

while (*temp1 != '\0') //while loop to loop through first string. goes as long as temp1 does not hit the end of the string
{
*final_string = *temp1; // sets each successive element of final string to equal each successive element of temp1
temp1++; // increments address of temp1 so it can feed a new element at a new address
final_string++; // increments address of final string so it can accept a new element at a new address
}
while (*temp2 != '\0') // same as above, except for string 2.
{
*final_string = *temp2;
temp2++;
final_string++;
}

*final_string = '\0'; // adds the null terminator thing to signify a string
return final_string; //returns the final string.
}

最佳答案

您正在返回 final_string,但它在您的算法过程中已递增以指向空终止符 - 而不是字符串的开头。

您需要将分配更改为:

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

然后是:

return final_string_return;

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

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