简体   繁体   English

C关于指针和数组的困惑

[英]C confusion about pointers and arrays

char a[]="HELLO";
char *p="HELLO";

will a[2] and p[2] fetch the same character? a[2]p[2]获取相同的字符?

What they will fetch is a char-sized chunk of memory located 2 char-sized steps (2 bytes here) after the beginning of each, or after the address in memory to which each var points. 他们将获取的是一个char大小的内存块,该内存块位于每个char大小的步骤后2个char大小的步骤(此处为2个字节),或者位于每个var指向的内存地址之后。 This happens to be 'L' i the example, but this is not the same address in memory. 在示例中,这恰好是“ L”,但这与内存中的地址不同。

So yes, in the example given, they will fetch the same character. 因此,是的,在给出的示例中,它们将获取相同的字符。

Yes. 是。

p[2] is equivalent to *(p+2) p [2]等于*(p + 2)

HELLO
  ^
*(p+2)

Should be noted, that the first "HELLO" will probably be stored in a writable memory page, while the second "HELLO" will probably be stored in a read only page. 应该注意的是,第一个“ HELLO”可能会存储在可写内存页面中,而第二个“ HELLO”可能会存储在只读页面中。 This is very closely related to the compiler / platform you are on. 这与您使用的编译器/平台紧密相关。

In both cases they will fetch an 'L' . 在两种情况下,它们都将获取'L' However, it isn't the same 'L' . 但是,它不是相同的'L' They are stored in different places. 它们存储在不同的位置。 That means if you compare their pointers, they will not be equal. 这意味着,如果您比较它们的指针,它们将不相等。

两者将具有相同的字符值。

I guess it depends on the compiler you use, but the answer is probably no. 我猜这取决于您使用的编译器,但答案可能是否定的。

By the way, you can test this easily by comparing the addresses of the two characters. 顺便说一句,您可以通过比较两个字符的地址来轻松测试。 If they differ, then: no. 如果它们不同,则:否。

Anyway, you shouldn't rely on this ;) 无论如何,您不应该依赖于此;)

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

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