[英]Why am I getting an error while concatenating 2 strings?
I know that dest is a pointer and it holds the address of dest[0], ie *dest would give me dest[0] so I basically wanted to change the value of (dest+l)(which is currently having address of '\0') to the address of src[0], but I am getting weird outputs.我知道 dest 是一个指针,它保存 dest[0] 的地址,即 *dest 会给我 dest[0] 所以我基本上想更改 (dest+l) 的值(当前地址为 ' \0') 到 src[0] 的地址,但我得到了奇怪的输出。
dest=final works then why does this code snippet fail? dest=final 有效,那么为什么这个代码片段会失败?
char* strcat(char* dest, char*src){
char* final;
int l=strlen(dest);
final=dest;
int b=0,i;
char* ans;
final+=l;
final=src;
final-=l;
dest=final;
printf("%s",final);
return dest;
}
EDIT: after reading the comments I made some changes to my code but now it gives me RE编辑:阅读评论后,我对代码进行了一些更改,但现在它给了我 RE
char* strct(char* dest, char*src){
char** final;
int l=strlen(dest);
*final=dest;
int b=0,i;
char* ans;
final+=l;
*final=src;
final-=l;
printf("%s",*final);
return *final;
}
The pointer to pointer version added nothing but extra stars and extra bugs, so lets ignore that one...指向指针版本的指针只添加了额外的星星和额外的错误,所以让我们忽略那个......
Now, what does the original code do:现在,原始代码做了什么:
final=dest;
Now final
points at dest
.dest
的final
点。final+=l;
Now final
points at the null terminator in dest
.final
点在dest
中的 null 终结器上。final=src;
Now final
points at src
and it forgets all about pointing at dest
.final
指向src
,它忘记了指向dest
。 This doesn't make sense.final=src
you should have done strcpy(final, src);
final=src
你应该做strcpy(final, src);
. dest
is large enough to contain the src
string to begin with.dest
足够大以包含开头的src
字符串。 A simpler implementation would be:一个更简单的实现是:
char* strcat (char* dest, const char* src)
{
strcpy(dest+strlen(dest), src);
return dest;
}
This is essentially the very same thing as you attempted, just less verbose.这与您尝试的基本相同,只是不那么冗长。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.