简体   繁体   English

我的strcat代码中的printf有什么问题?

[英]What's wrong with printf in my strcat code?

I have made this program to emulate strcat functionality but there is an error with printf which I don't understand... 我已经制作了该程序来模拟strcat功能,但是printf出现错误,我不明白...

Here is the code: 这是代码:

#include <stdio.h>

char *mystrcat(char *s1, char *s2);

int main(void)
{
    char *s1,*s2;
    s1="asdad";
    s2="asdad";
    s1=mystrcat(s1,s2);
    printf(s1);

    return 0;
}
char *mystrcat(char *s1,char *s2)
{
    int i,j;
    for(i=0;s1[i]<'\0';i++) ;
    for(j=0;s2[j]!='\0';j++) s1[i+j]=s2[j];
    s1[i+j]='\0';
    return s1;
}

至少s1[i] < '\\0's1[i] < 0 ,始终为假。

The first problem is that s1 doesn't have enough space to append s2 to it. 第一个问题是s1没有足够的空间来将s2附加到它。 You need the size of the buffer pointed to by s1 to be at least strlen(s1) + strlen(s2) + 1 (the + 1 being the NUL terminator). 您需要s1指向的缓冲区的大小至少为strlen(s1) + strlen(s2) + 1+ 1是NUL终止符)。

The second problem is that string literals are read-only. 第二个问题是字符串文字是只读的。 You assign s1 from "asdad" , which creates a pointer to (potentially) read-only memory. 您从"asdad"分配s1 ,这将创建一个指向(可能是)只读内存的指针。 Of course the first problem means that you wouldn't have enough space to append to the end even if it were writeable, but this is one of the common pitfalls in C and worth mentioning. 当然,第一个问题意味着即使可写,您也没有足够的空间可以追加到末尾,但这是C语言中常见的陷阱之一,值得一提。

Third problem (already mentioned in another answer ) is that the comparison s1[i] < '\\0' is wrong and you will not correctly find the length of s1 since the loop will not run even a single iteration. 第三个问题(已经在另一个答案中提到)是比较s1[i] < '\\0'是错误的,您将无法正确找到s1的长度,因为循环甚至不会执行一次迭代。 The correct condition is the same as in your second loop, != '\\0' . 正确的条件与第二个循环!= '\\0' (This masks problem 1 since then you are inadvertently overwriting s1 from the beginning.) (这掩盖了问题1,因为从那时起您无意间覆盖了s1 。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM