【发布时间】:2014-10-23 14:45:33
【问题描述】:
所以我必须创建一个函数来连接 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.
}
【问题讨论】:
-
不要在 C 中转换
malloc。 -
在此处发布时请正确缩进您的代码。
-
*final_string = '\0'; return final_string;