简体   繁体   English

使用char指针声明的字符串的内存地址

[英]Memory address of strings declared using a char pointer

I read that when you declare strings using a pointer, the pointer contains the memory address of the string literal. 我读到,当您使用指针声明字符串时,指针包含字符串文字的内存地址。 Therefore I expected to get the memory address from this code but rather I got some random numbers. 因此,我期望从此代码中获取内存地址,但是我得到了一些随机数。 Please help me understand why it didn't work. 请帮助我了解为什么它不起作用。

int main()
{
    char *hi = "Greeting!";
    printf("%p",hi);
    return(0);
}

If the pointer hi contains the memory address of the string literal, then why did it not display the memory address? 如果指针hi包含字符串文字的内存地址,那么为什么它不显示内存地址呢?

It did work. 它确实起作用。 It's just that you can consider the address as being arbitrarily chosen by the C runtime. 只是您可以认为该地址是C运行时任意选择的。 hi is a pointer set to the address of the capital G in your string. hi是设置为字符串中大写G地址的指针。 You own all the memory from hi up to and including the nul-terminator at the end of that string. 您拥有所有的内存,从hi到该字符串末尾的nul-terminator。

Also, use const char *hi = "Greeting!"; 另外,使用const char *hi = "Greeting!"; rather than char * : the memory starting at hi is read-only . 而不是char * :从hi开始的内存是只读的 Don't try to modify the string: the behaviour on attempting to do that is undefined . 不要尝试修改字符串:尝试执行该操作的行为是undefined

The "random numbers" you got are the Memory addresses. 您获得的“随机数”是内存地址。 They are not constant, since on each execution of your program, other Memory addresses are used. 它们不是常数,因为在每次执行程序时,都会使用其他内存地址。

A pointer could be represented in several ways. 指针可以几种方式表示。 The format string "%p" "writes an implementation defined character sequence defining a pointer" link . 格式字符串"%p" “写入定义指针的实现定义的字符序列” 链接 In most cases, it's the pointed object's address interpreted as an appropriately sized unsigned integer, which looks like "a bunch of random number". 在大多数情况下,它是将指向对象的地址解释为适当大小的无符号整数,看起来像“一堆随机数”。

A user readable pointer representation is generally only useful for debugging. 用户可读的指针表示形式通常仅对调试有用。 It allows you to compare two different representations (are the pointers the same?) and, in some cases, the relative order and distance between pointers (which pointer comes "first", and how far apart are they?). 它使您可以比较两个不同的表示形式(指针是否相同?),在某些情况下还可以比较指针之间的相对顺序和距离(哪个指针排在“第一个”位置,以及它们相距多远?)。 Interpreting pointers as integers works well in this optic. 将指针解释为整数在此光学系统中效果很好。

It would be helpful to us if you could clarify what output you expected. 如果您能弄清预期的输出结果,将对我们有所帮助。 Perhaps you expected pointers to be zero-based? 也许您希望指针从零开始?

Note that, while some compilers might accept your example, it would be wiser to use const char * . 请注意,尽管某些编译器可能接受您的示例,但使用const char *会更明智。 Using a char * would allow you to try to modify your string literal, which is undefined behavior. 使用char *将允许您尝试修改字符串文字,这是未定义的行为。

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

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