代码之家  ›  专栏  ›  技术社区  ›  Humphrey Bogart

不同的字符串初始化产生不同的行为?

c
  •  1
  • Humphrey Bogart  · 技术社区  · 15 年前

    while (*postcode) {
        *postcode = toupper(*postcode);
    
        postcode++;
    }
    

    char wrong[20];
    strcpy(wrong, "la1 4yt");
    

    但是下面这些,尽管它们是一样的,不是吗?

    char* wrong = "la1 4yt";
    

    我的程序在试图写入非法地址时崩溃(我想是segfault)。这是一个问题吗 malloc 惯性导航与制导?不被诅咒?不应该是。。。

    通过调试,我注意到它在尝试将第一个字符指定为大写时崩溃。

    感谢您的帮助!

    5 回复  |  直到 15 年前
        1
  •  5
  •   John Kugelman Michael Hodel    15 年前
    char* wrong = "la1 4yt";
    

    这声明了一个指向字符串常量的指针。无法修改该常量,这就是代码崩溃的原因。如果你写得更迂腐

    const char* wrong = "la1 4yt"; // Better
    

    然后编译器会发现错误。您可能应该在任何时候声明指向字符串文字的指针而不是创建数组时执行此操作。

    另一方面,它为20个字符分配读/写存储,因此可以向空间写入。

    char wrong[20];
    

    如果您想将其初始化为上面的字符串,您可以这样做,然后允许更改它。

    char wrong[20] = "la1 4yt"; // Can be modified
    char wrong[]   = "la1 4yt"; // Can be modified; only as large as required
    
        2
  •  2
  •   ezpz    15 年前
    char * whatever = "some cont string";
    

        3
  •  2
  •   Michael    15 年前

    在第二种变体中, "la1 4yt" 是常量,因此位于只读段中。只有指针( wrong

    这个可能很有趣: http://eli.thegreenplace.net/2009/10/21/are-pointers-and-arrays-equivalent-in-c/

        4
  •  2
  •   Sinan Ünür    15 年前

    Question 8.5 在C常见问题列表中。

        5
  •  1
  •   pmg    15 年前

    当你这样做的时候

    char wrong[20] = "la1 4yt";
    

    编译程序 副本 {'l', 'a', '1', ' ', '4', 'y', 't', '\0'} 到的相应元素 wrong 阵列;当你这样做的时候

    char *wrong = "la1 4yt";
    

    编译器分配给 错误的 字符串文本的地址。

    字符串文字是 char[] (字符数组),而不是 const char[] ... 但是你不能改变他们!!

    6.4.5 String literals
    6   It is unspecified whether these arrays are distinct provided
        their elements have the appropriate values. If the program
        attempts to modify such an array, the behavior is undefined.
    

    当我使用字符串文字来初始化 char * const 根据定义。

    const char *wrong = "la1 4yt";
    

    假设你有

    char *test1 = "example test";
    char *test2 = "test";
    

    编译器创建了1个单字符串文本,并使用该单字符串文本初始化test1和test2。如果允许您更改字符串文字。。。

    test1[10] = 'x';       /* attempt to change the 's' */
    printf("%s\n", test2); /* print "text", not "test"! */