简体   繁体   English

在初始化期间为指针指定字符串值时究竟会发生什么?

[英]What exactly happens when pointers are assigned with strings values during initialization?

I'm quite confused because from what I've learned, pointers store addresses of the data they are pointing to. 我很困惑,因为从我学到的东西,指针存储了他们指向的数据的地址。 But in some codes, I see strings often assigned to pointers during initialization. 但在某些代码中,我看到在初始化期间经常分配给指针的字符串。

What exactly happens to the string? 字符串究竟发生了什么?
Does the pointer automatically assign an address to store the string and point itself to that address? 指针是否自动指定一个地址来存储字符串并将其自身指向该地址?
How does "dereferencing" works in pointers to strings? “解除引用”如何在指向字符串的指针中起作用?

In case of 的情况下

char *p = "String";

compiler allocate memory for "String" , most likely "String" is stored in read only data section of memory, and set pointer p to points to the first byte of that memory address. 编译器为"String"分配内存,很可能"String"存储在内存的只读数据部分,并将指针p设置为指向该内存地址的第一个字节。

p --------------+
                |
                |
                V
             +------+------+------+------+------+------+------+
             |      |      |      |      |      |      |      |
             | 'S'  | 't'  | 'r'  | 'i'  | 'n'  | 'g'  | '\0' |
             |      |      |      |      |      |      |      |
             +------+------+------+------+------+------+------+
              x100    x101   x102   x103   x104   x105   x106

Q: I see strings often assigned to pointers during initialization. 问:我看到在初始化期间经常分配给指针的字符串。

I think, what you are calling as string is actually a string literal . 我认为,你所谓的字符串实际上是一个字符串文字

According to C11 standard, chapter §6.4.5 根据C11标准,第§6.4.5章

A character string literal is a sequence of zero or more multibyte characters enclosed in double-quotes, as in "xyz" . 字符串文字是用双引号括起来的零个或多个多字节字符的序列,如"xyz" [...] [...]

The representation, "xyz" produces the address of the first element of the string literal which is then stored into the pointer, as you've seen in the initialization time. 表示"xyz"产生字符串文字的第一个元素的地址,然后存储到指针中,正如您在初始化时看到的那样。

Q: Does the pointer automatically assign an address to store the string and point itself to that address? 问:指针是否自动分配一个地址来存储字符串并将其自身指向该地址?

A: No, the memory for storing the string literal is allocated at compile time by the compiler. 答:不可以,编译器在编译时分配用于存储字符串文字的内存。 Whether a string literal is stored in a read only memory or read-write memory is compiler dependent. 字符串文字是存储在只读存储器还是读写存储器中是依赖于编译器的。 Standard only mentions that any attempt to modify a string literal results in undefined behavior . 标准仅提到任何修改字符串文字的尝试都会导致未定义的行为

Q: How does "dereferencing" works in pointers to strings? 问:“解除引用”如何在指向字符串的指针中起作用?

A: Just the same way as it happens in case of another pointer to any other variable. 答:就像另一个指向任何其他变量的指针一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM