【问题标题】:Why does malloc give different addresses on "b" and "b[0]"?为什么 malloc 在“b”和“b[0]”上给出不同的地址?
【发布时间】: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", &amp;b); 需要是 printf("\n Address of b : %x", b); 而没有 &amp;。因为你问的是指针所在的位置,而不是它的值。顺便说一句,指针请使用%p 格式,并将参数转换为(void*)b
  • 因为 b 的地址与其内容指向的地址不同。
  • &amp;a&amp;a[0] 指向同一个地方的结果是因为a 是一个数组。 b 是一个指针,而不是一个数组。
  • 因为指针不是数组。
  • "解释 malloc 的这种行为,即 b 不同于 b[0]?" --> 发表您的想法将澄清您的问题。你期待什么?

标签: c pointers malloc


【解决方案1】:

b 是一个局部变量,驻留在堆栈上。它的值被解释为一个指针。 当 malloc 在(堆)上分配内存时,您将该地址分配给b,所以现在b 是一个指针(它仍然存储在堆栈上的同一位置),并指向堆上的一个数组。

b[0] 是该数组中的第一个元素。

相比之下,a 是一个完全在本地分配的数组,因此它完全驻留在堆栈上——这使得a 成为数组本身,所以a[0] 是相同的。尝试将 malloc 返回值分配给a,看看会发生什么。

【讨论】:

    【解决方案2】:
    • &amp;b变量的地址,名为b。该变量恰好指向某个数组,但这在这里无关紧要。
    • &amp;b[0]b 指向的数组的第一个元素的地址。换句话说,它与b + 0 相同,所以在这种情况下它是b 的值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-06
      • 2016-06-02
      • 2014-03-29
      • 2011-02-02
      • 1970-01-01
      • 1970-01-01
      • 2019-04-30
      • 2011-05-30
      相关资源
      最近更新 更多