考虑以下 C 中的两个语句。两者之间有什么区别?
以下是主要区别:
语句 ' char s[] = “52cxydh” ' 创建一个字符数组,它与任何其他数组一样,我们可以执行所有数组操作。这个数组唯一特别的地方是,虽然我们用 7 个元素初始化了它,但它的大小是 8(编译器自动添加了 ' ')
输出:
输出:
char s[] = "52cxydh";
char *s = "52cxydh";
#include <stdio.h>
int main()
{
char s[] = "52cxydh";
printf("%lu", sizeof(s));
s[0] = 'j';
printf("n%s", s);
return 0;
}
10 j2cxydh语句 ' char *s = “52cxydh” ' 创建一个字符串文字。大多数编译器将字符串文字存储在内存的只读部分中。C 和 C++ 标准说字符串文字具有静态存储持续时间,任何修改它们的尝试都会产生未定义的行为。 s只是一个指针,并且像任何其他指针一样存储字符串文字的地址。
#include <stdio.h>
int main()
{
char *s = "52cxydh";
printf("%lu", sizeof(s));
// Uncommenting below line would cause undefined behaviour
// (Caused segmentation fault on gcc)
// s[0] = 'j';
return 0;
}
8
运行上面的程序可能还会产生一个警告“警告:不推荐使用从字符串常量到'char *'的转换”。出现此警告是因为 s 不是 const 指针,而是存储只读位置的地址。指向 const 的指针可以避免警告。
#include <stdio.h>
int main()
{
const char *s = "52cxydh";
printf("%lu", sizeof(s));
return 0;
}