字符串:指针与字符数组 [英] String literals: pointer vs. char array
问题描述
在此语句:
的char * A =字符串1
到底什么是字符串?它是字符串1
?因为在C 这个线程字符串字面说不同的东西。
到了我的知识
INT的main()
{
字符* A =字符串1; //为只读段分配的内存与字符串文字。
焦B〔] =字符串2; //就是内存将在堆栈中分配的字符数组。 一个[0] =X; //不允许。这是一个未定义行为。对我来说,赛格故障。
B [0] ='Y'; //有效。 返回0;
}
请添加上述以外的一些细节提到的观点。谢谢你。
调试输出显示错误 A [0] ='Y';
从/home/jay/Desktop/MI/chararr/a.out...done阅读的符号。
(GDB)b主
在0x40056c断点1:文件ddd.c,4号线。
(GDB)R
启动程序:/home/jay/Desktop/MI/chararr/a.out断点1,主要的()在ddd.c:4
4 {
(GDB)N
6字符* A =字符串1;
(GDB)N
7 CHAR B〔] =字符串2;
(GDB)
9 [0] =Y;
(GDB)计划接收信号SIGSEGV,分割过错。
0x0000000000400595在main()在ddd.c:9
您可以看一下字符串作为的用双引号包围的字符序列的。
该字符串的保存在只读存储器并试图修改此内存导致的未定义行为
那么怎么来的,你得到段错误?的结果
- 主要的一点是,的char * PTR =字符串
,使 PTR
指向只读存储器在您的字符串存储。所以,当您尝试访问该存储器: PTR [0] ='X'
(这是由方式等同于 *(PTR + 0) ='X'
),它是一个内存访问冲突
在另一方面:字符B〔] =字符串2;
分配内存和拷贝字符串字符串2
进去,从而改变它是有效的。当 B
超出范围,此内存被释放。
In this statement:
char *a = "string1"
What exactly is string literal? Is it string1
? Because this thread String literals in C says something different.
Up to my knowledge
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;
}
Please add some details other than above mentioned points. Thanks.
Debug Output Showing error in 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
You can look at string literal as "a sequence of characters surrounded by double quotes". This string is stored at read-only memory and trying to modify this memory leads to undefined behavior.
So how come that you get segmentation fault?
- 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.
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.
Have a look at Literal string initializer for a character array
这篇关于字符串:指针与字符数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!