【发布时间】:2017-01-21 19:22:56
【问题描述】:
我在课堂上有这个例子,但没有适当的解释:
#include<stdio.h>
#include<stdlib.h>
int main() {
const int dim = 10;
int i, a[dim], *b;
b = (int *)malloc(dim*sizeof(int));
printf("\n Address of a : %x", &a);
printf("\n Address of a[0]: %x", &a[0]);
printf("\n Dimension of a : %d bytes", sizeof(a));
printf("\n Address of b : %x", &b);
printf("\n Address of b[0]: %x", &b[0]);
printf("\n Dimension of b : %d bytes", sizeof(b));
free(b);//free allocated memory
return 0;
}
谁能解释一下 malloc 的这种行为,即 b 与 b[0] 不同?
Address of a : ffffcb90
Address of a[0]: ffffcb90
Dimension of a : 40 bytes
Address of b : ffffcbc0
Address of b[0]: 103a0
Dimension of b : 8 bytes
【问题讨论】:
-
printf("\n Address of b : %x", &b);需要是printf("\n Address of b : %x", b);而没有&。因为你问的是指针所在的位置,而不是它的值。顺便说一句,指针请使用%p格式,并将参数转换为(void*)b。 -
因为 b 的地址与其内容指向的地址不同。
-
&a与&a[0]指向同一个地方的结果是因为a是一个数组。b是一个指针,而不是一个数组。 -
因为指针不是数组。
-
"解释 malloc 的这种行为,即 b 不同于 b[0]?" --> 发表您的想法将澄清您的问题。你期待什么?