代码之家  ›  专栏  ›  技术社区  ›  Ashish Yadav

为什么这个代码会崩溃?[副本]

  •  6
  • Ashish Yadav  · 技术社区  · 14 年前

    为什么这个代码会崩溃? 正在使用 strcat 字符指针非法?

    #include <stdio.h>
    #include <string.h>
    
    int main()
    {
       char *s1 = "Hello, ";
       char *s2 = "world!";
       char *s3 = strcat(s1, s2);
       printf("%s",s3);
       return 0;
    }
    

    请给出引用数组和指针的正确方法。

    3 回复  |  直到 14 年前
        1
  •  11
  •   James McNellis    14 年前

    问题是 s1 指向一个字符串文本,您正试图通过附加 s2 为了它。不允许修改字符串文本。您需要创建一个字符数组并将两个字符串都复制到其中,如下所示:

    char *s1 = "Hello, ";
    char *s2 = "world!";
    
    char s3[100] = ""; /* note that it must be large enough! */
    strcat(s3, s1);
    strcat(s3, s2);
    printf("%s", s3);
    

    “足够大”至少意味着 strlen(s1) + strlen(s2) + 1 . 这个 + 1 将解释空终止符。

    已经说过了,你应该认真考虑使用 strncat (或者可以说更好但不标准的 strlcat ,如果可用的话),这是边界检查,因此远优于 strcat .

        2
  •  1
  •   penguin4hire    14 年前

    在这种情况下,正确的方法是在目标字符串(s1)中分配足够的空间来存储6个额外字符(s2)以及字符串的空终止符。

    char s1[14] = "Hello, ";
    char *s2 = "world!";
    char *s3 = strcat(s1, s2);
    printf("%s",s3);
    
        3
  •  0
  •   Opera    14 年前

    这里引用strcat()手册中的一句话:“strcat()函数将src字符串附加到dest字符串,覆盖dest末尾的空字节(“\0”),然后添加一个终止的空字节。字符串不能重叠,dest字符串必须有足够的空间来存放结果。“

    这里的问题是,s1和s2指向的静态字符串是“只读的”,因此如果您尝试执行strcat操作,在dest参数中使用这样的字符串,则会得到一个错误。

    在这里创建hello world字符串的最好方法是malloc它,这样它就可以同时包含s1和s2。另外,不要忘记在printf格式字符串的末尾添加一个'\n',否则您可能会感到惊讶。

    这是如果我是你,我会写的代码:

    
    int main()
    {
      char* s1 = "Hello ";
      char* s2 = "World !";
      char *s3 = malloc((strlen(s1) + strlen(s2) + 1) * sizeof(char));
    /* +1 is for the null terminating character
    and sizeof(*s3) is the actual size of a char. */
    
      if (s3)
      {
        strcat(s3, s1);
        strcat(s3, s2);
        printf("%s\n", s3);
        free(s3); // always free what you alloc when you don't need it anymore.
      }
      return 0;
    }