unsigned char *dup = malloc(size);
My question may be naive. What does dup[2]
mean? 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. Many thanks for your time.
dup[2]
is sematically identical to *(dup + 2)
. So it is the value of the third byte pointed to by 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.
it's the value of the third char from the malloced memory?
This.
dup[2]
equivalent to *(dup + 2)
. The + 2
implicitly acts like + 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)
.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.