[英]Concatenate two strings without using strcat
I wrote a function to concatenate two strings ( s
= "computer"
; t
= "keyboard"
), but my code only returns "keyboard"
.我写了一个 function 来连接两个字符串(
s
= "computer"
; t
= "keyboard"
),但我的代码只返回"keyboard"
。 Please point out the mistakes.请指出错误。
char *concat(char *s, char *t) {
s = malloc((strlen(s) + strlen(t) + 1) * sizeof(char));
char *p = s;
while (*p != '\0') {
++p;
}
while (*t != '\0') {
*p++ = *t++;
}
*p = '\0';
return s;
}
I do not want to use strcat()
.我不想使用
strcat()
。 This is a test program from Stepik, so I cannot change anything in the main
function.这是来自 Stepik 的测试程序,因此我无法更改
main
function 中的任何内容。 Here is the question: Write a function which receives two character pointers and returns a new character pointer representing their concatenation.这是问题:编写一个 function 接收两个字符指针并返回一个表示它们连接的新字符指针。
char *myconcat(const char *s1, const char *s2)
{
size_t len1,len2;
char *result = malloc((len1 = strlen(s1)) + (len2 = strlen(s2)) + 1);
if(result)
{
memcpy(result, s1, len1);
memcpy(result + len1, s2, len2 + 1);
}
return result;
}
You have s="computer" when passed into a function, and then on the very first line you reassign it with malloc, so "computer" is gone.当传递给 function 时,你有 s="computer",然后在第一行你用 malloc 重新分配它,所以“computer”消失了。 You can debug your program step by step, or just print the values to the console.
您可以逐步调试程序,也可以将值打印到控制台。 This will help you to find the error.
这将帮助您找到错误。
You are on the right track:你走在正确的轨道上:
Yet there are some issues:然而也存在一些问题:
malloc()
,malloc()
返回的指针覆盖指向第一个字符串的指针,const char *
as you do not modify these strings. const char *
因为您不修改这些字符串。 Here is a corrected version:这是一个更正的版本:
#include <stdlib.h>
#include <string.h>
char *concat(const char *s, const char *t) {
char *ret = malloc((strlen(s) + strlen(t) + 1) * sizeof(char));
char *p = ret;
while (*s != '\0') {
*p++ = *s++;
}
while (*t != '\0') {
*p++ = *t++;
}
*p = '\0';
return ret;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.