[英]What does pointer array from malloc mean?
unsigned char *dup = malloc(size);
My question may be naive. 我的问题可能很幼稚。 What does
dup[2]
mean? dup[2]
是什么意思? Is it a pointer to the third char from the malloced memory or it's the value of the third char from the malloced memory? 它是从已分配内存中指向第三个字符的指针,还是从已分配内存中第三个字符的值? I have searched google but found no result to explain this.
我已经搜索过google,但没有找到解释此结果的结果。 Many thanks for your time.
非常感谢您的宝贵时间。
dup[2]
is sematically identical to *(dup + 2)
. dup[2]
在语义上与*(dup + 2)
。 So it is the value of the third byte pointed to by dup
. 因此,它是
dup
指向的第三个字节的值。 That is, the memory addresses are: 也就是说,内存地址为:
dup, dup+1, dup+2, ....., dup+size-1
Note that malloc
does not initialize the returned memory, so strictly speaking, the value of dup[2]
could be anything. 请注意,
malloc
不会初始化返回的内存,因此严格来说, dup[2]
的值可以是任何值。
it's the value of the third char from the malloced memory?
是分配的内存中第三个字符的值吗?
This. 这个。
dup[2]
equivalent to *(dup + 2)
. dup[2]
等效于*(dup + 2)
。 The + 2
implicitly acts like + 2 * sizeof(char)
. + 2
隐含的行为类似于+ 2 * sizeof(char)
。
If you want a pointer to the third char in the memory, without dereferencing it, then you just use the same as above. 如果要在不取消引用的情况下指向内存中第三个字符的指针,则只需使用与上述相同的字符即可。 without the dereferencing operator:
没有取消引用运算符:
unsigned char *thirdChar = dup + 2;
Clearly, dup[k]
in this case representing the third character of the string, which is very much similiar to *(dup + 2)
. 显然,在这种情况下
dup[k]
表示字符串的第三个字符,与*(dup + 2)
非常相似。
The supporting code as follows: 支持代码如下:
#include<stdio.h>
#include<string.h>
int main() {
unsigned char *dup = malloc(10);
scanf("%s", dup);
printf("%c", dup[2]);
printf("\n%c", *(dup+2));
return 0;
}
The output being the same for both printf
statement, it made it very clear. 两个
printf
语句的输出相同,这非常清楚。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.