C 语言中 char s[] 和 char *s 的区别
我们有时会看到字符串使用 char s[] 构建,有时使用 char *s 构建。因此,我们在这里要看它们是否有不同或完全相同?
存在一些差异。s[] 是一个数组,但 *s 是一个指针。例如,如果有两个声明,分别是 char s[20] 和 char *s,那么使用 sizeof(),我们分别得到 20 和 4。第一个将是 20,因为它显示该数据有 20 个字节。但第二个仅显示 4,因为这是一个指针变量的大小。对于一个数组,整个字符串存储在堆栈部分,但对于一个指针,指针变量存储在堆栈部分,而内容存储在代码部分。最重要的是,我们无法编辑指针类型字符串。因此这是只读的。但我们可以编辑字符串的数组表示。
示例
#include<stdio.h> main() { char s[] = "Hello World"; s[6] = 'x'; //try to edit letter at position 6 printf("%s", s); }
输出
Hello xorld Here edit is successful. Now let us check for the pointer type string.
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
示例
#include<stdio.h> main() { char *s = "Hello World"; s[6] = 'x'; //try to edit letter at position 6 printf("%s", s); }
输出
Segmentation Fault
广告