吾爱程序员:这里有好玩的游戏和软件
当前位置:首页C语言教程 → C 中的 char s[] 和 char *s 有什么区别?

C 中的 char s[] 和 char *s 有什么区别?

来源:网络 | 更新时间:2022-01-13 07:23:06
考虑以下 C 中的两个语句。两者之间有什么区别? 
 char s[] = "52cxydh";
char *s = "52cxydh";
以下是主要区别: 语句 ' char s[] = “52cxydh ' 创建一个字符数组,它与任何其他数组一样,我们可以执行所有数组操作。这个数组唯一特别的地方是,虽然我们用 7 个元素初始化了它,但它的大小是 8(编译器自动添加了 '') 
#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;
}
 

最新文章

热点资讯

手游排行榜

CopyRight 2020-2030吾爱程序员

鄂ICP备2021004581号-8

本站资源收集于网络,如有侵权请联系我们:35492删除0109@qq.com