使指针的中间;它有效吗?

Making the middle of a pointer NUL; does it work?

本文关键字:有效 指针 中间      更新时间:2023-10-16

可能的重复:
在C字符串中" 0"后的内存会发生什么?

可以制作指针的第三元素nul(' 0'),然后"擦除"指针剩余的元素?

假设您在谈论C风格字符串,那么是:

char s[] = "abcdefgh";   // s = "abcdefgh"
                         // (actually contains 9 characters: "abcdefgh")
s[3] = '';             // s = "abc"
                         // (still contains 9 characters, but now: "abcefgh")

请注意,此时s[3]之外的字符尚未神奇地消失 - 只是显示字符串或将其传递到采用C风格字符串的任何功能,导致字符串仅显示为包含三个字符。您仍然可以做,例如

s[3] = 'x';              // s = "abcxefgh"
                         // (still contains 9 characters, but now: "abcxefgh")