字符串文字:指针与字符数组 [英] String literals: pointer vs. char array

查看:39
本文介绍了字符串文字:指针与字符数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此声明中:

char *a = "string1"

字符串字面量到底是什么?是 string1 吗?因为这个线程 C 和 C++ 中字符串文字的类型是什么? 说的有些不同.

What exactly is string literal? Is it string1? Because this thread What is the type of string literals in C and C++? says something different.

据我所知

int main()
{
    char *a = "string1"; //is a string- literals allocated memory in read-only section.
    char b[] = "string2"; //is a array char where memory will be allocated in stack.

    a[0] = 'X'; //Not allowed. It is an undefined Behaviour. For me, it Seg Faults. 
    b[0] = 'Y'; //Valid. 

    return 0;
} 

请添加除上述要点以外的一些细节.谢谢.

调试输出显示错误 a[0] = 'Y';

Reading symbols from /home/jay/Desktop/MI/chararr/a.out...done.
(gdb) b main
Breakpoint 1 at 0x40056c: file ddd.c, line 4.
(gdb) r
Starting program: /home/jay/Desktop/MI/chararr/a.out 

Breakpoint 1, main () at ddd.c:4
4   {
(gdb) n
6   char *a = "string1";
(gdb) n
7   char b[] = "string2";
(gdb) 
9   a[0] = 'Y';
(gdb) 

Program received signal SIGSEGV, Segmentation fault.
0x0000000000400595 in main () at ddd.c:9

推荐答案

您可以将字符串字面量视为由双引号括起来的字符序列".此字符串应被视为只读,尝试修改此内存会导致未定义行为.它不一定存储在只读内存中,类型是char[]而不是const char[],但它仍然是未定义的行为.类型不是 const 的原因是向后兼容.C 在开始时没有 const 限定符.在 C++ 中,字符串文字的类型为 const char[].

You can look at string literal as "a sequence of characters surrounded by double quotes". This string should be treated as read-only and trying to modify this memory leads to undefined behavior. It's not necessarily stored in read only memory, and the type is char[] and not const char[], but it is still undefined behavior. The reason the type is not const is backwards compability. C didn't have the const qualifier in the beginning. In C++, string literals have the type const char[].

那你怎么会出现分段错误?

  • 重点是 char *ptr = "string literal" 使 ptr 指向存储字符串文字的只读内存.因此,当您尝试访问此内存时: ptr[0] = 'X' (顺便说一下,相当于 *(ptr + 0) = 'X'),这是一个内存访问冲突.
  • The main point is that char *ptr = "string literal" makes ptr to point to the read-only memory where your string literal is stored. So when you try to access this memory: ptr[0] = 'X' (which is by the way equivalent to *(ptr + 0) = 'X'), it is a memory access violation.

另一方面:char b[] = string2"; 分配内存并将字符串string2" 复制到其中,因此修改它是有效的.当 b 超出范围时,此内存被释放.

On the other hand: char b[] = "string2"; allocates memory and copies string "string2" into it, thus modifying it is valid. This memory is freed when b goes out of scope.

查看字符数组的文字字符串初始值设定项

这篇关于字符串文字:指针与字符数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆