声明的含义
我多次遇到过 char* ch = "hello";
语句。
我知道 char* ch
告诉 ch
是指向 char
的指针。但是将 hello 分配给 ch 意味着什么?
我无法理解这一点?请帮忙。
I have many times come across the statement char* ch = "hello";
.
I understand that char* ch
tells that ch
is a pointer towards a char
. But what does assigning hello to ch mean ?
I cannot undestand this ? please help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这意味着
ch
是一个指向字符的指针。当您执行char* ch = "hello"
时,ch
将指向第一个字符,即字符h
。要指向第二个字符,可以执行ch + 1
或ch[1]
。请注意,理想情况下,ch
的类型应为const char*
,因为您无法写入指向的内存位置。It means
ch
is a pointer to a character. When you dochar* ch = "hello"
ch
will be pointing to the first character i.e. characterh
. To point to the second character, you can doch + 1
orch[1]
. Note that ideally the type ofch
should have beenconst char*
as you can not write to the pointed memory location.字符串文字静态存储在程序二进制文件内的某个位置。它们很可能被加载到内存中的只读“数据”部分,但这是未定义的行为。
分配字符串文字只需传递第一个字节的地址;在本例中,
char* ch
指向“hello”中的“h”。注意:修改静态字符串是未定义的行为!虽然您可以获得指针,但任何赋值都是危险的。
String literals are stored statically somewhere inside the program binary. They are most likely loaded into a readonly 'data' section in memory, but this is undefined behavior.
Assigning a string literal simply passes the address of the first byte; in this case,
char* ch
points to the 'h' in "hello".Note: Modifying static strings is undefined behavior! While you can get a pointer, any assignment is dangerous.
这里发生了几件事。
"hello"
等于{ 'h', 'e', 'l', 'l', 'o', '\0' }
。即,它是一个字符数组。数组可以隐式转换为相应的指针类型。因此,这里的语句实际上创建了一个(静态)字符数组,并将指向第一个元素的指针分配给变量ch
(顺便说一句,命名不好)。There are several things happening here.
"hello"
is equal to{ 'h', 'e', 'l', 'l', 'o', '\0' }
. I.e., it is an array of characters. Arrays can be implicitly converted to the corresponding pointer type. So the statement here really creates a (static) array of characters, and assigns the pointer to the first element to the variablech
(bad naming, by the way).该语句编译为:
0x8048494 处的字符串是“hello\0”,如 xxd 所示:
the statement compiles to:
the string at 0x8048494 is "hello\0" as seen here from xxd: