简体   繁体   English

我的串联操作有什么问题?

[英]What is Wrong with My Concatenation Operation?

I was trying to implement strcat() , so I came up with this code. 我试图实现strcat() ,所以我想到了这段代码。 But, I don't know what is wrong with it? 但是,我不知道这是怎么回事? It's giving me segmentation fault. 这给了我细分错误。

I was thinking that this might be a memory allocation mess? 我以为这可能是内存分配混乱? Is that it? 是吗 How can I fix it without using malloc() ? 不使用malloc()怎么解决?

#include <stdio.h>

char *strcat(char *s,char *d){

 while(*s++ != '\0') ;
 while(*s++ = *d++) ;

 *s = '\0';

 return s;
}

int main(){

char s[20]= "source";
char d[20]= "dest";

printf("%s\n",strcat(s,d));

return 0;
}

I have to concat d ahead of s . 我必须Concat的d提前s

  1. The strings are in read only memory 字符串在只读存储器中
  2. The string s will not be long enough 字符串s不会足够长

To fix: 修理:

   ...
   #define S_STR "source"

   char *d= "dest";
   char *s= S_STR;
   s = malloc(strlen(s) + strlen(d) + 1);
   strcpy(s, S_STR);
   printf("%s\n",strcat(s,d));
   free(s);
   return 0;
}

The s, d are string constants! s,d是字符串常量! You should never do such things. 你绝对不应该做这样的事情。 have a big array like char s[100], copy source to it, and then use your concatenation. 有一个像char s [100]这样的大数组,将源复制到它,然后使用串联。 Remember that s should have room to accomodate the content of d! 请记住,s应该有空间容纳d的内容!

i fixed it 我修好了它

#include <stdio.h>
#define SIZE 20

char *strocat(char *s,char *d){

 char *temp = s;

 while(*s++ != '\0');
 *--s;
 while(*s++ = *d++);

 *s = '\0';

 return temp;
}

int main(){

char s[SIZE] = "source";
char d[SIZE] = "dest";

printf("%s\n",strocat(s,d));

return 0;
}

The strings s and d you declared are constant string literals,You can't modify them. 您声明的字符串s和d是常量字符串文字,您无法修改它们。 you should declare two char arrays and make sure the one you are copying to is big enough to hold the other. 您应该声明两个char数组,并确保要复制到的一个足以容纳另一个char数组。

#include <stdio.h>

char *strcat(char *s,char *d)
{
    //Get length of s string
    size_t len = strlen(s);

    //declare new pointer and assign it the value of s
    char *ptr = s;

    //move the pointer to the end of the string
    ptr += len;

    //copy contentes of d string to s string
    while( *d != '\0' )
    {
        *ptr++ = *d++;
    }

    *ptr = '\0';

    //return s
    return s;
}

int main()
{
    //make sure s array length is big enough to accomodate d string
    char s[50] = "source";

    char d[] = "dest";

    printf("%s\n",strcat(s,d));

    return 0;
}

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

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