【问题标题】:Why does it keep saying the capacity of my dynamic array is 2 even though I keep changing it so it is not 2? [duplicate]为什么它一直说我的动态数组的容量是 2,即使我一直在改变它,所以它不是 2? [复制]
【发布时间】:2019-11-18 15:17:48
【问题描述】:

我想把我的动态数组的容量打印出来,但是不管怎么改,总是说两个数组的容量都是2。

代码(tmp.c)

#include <stdio.h>
#include <stdlib.h>

int main(){

  int *ptr1 = (int *)malloc(sizeof(int) * 3);
  int capacity_ptr1 = sizeof(ptr1)/sizeof(int);
  printf("capacity of ptr1 is: %d\n", capacity_ptr1 );

  int *ptr2 = (int *)realloc(ptr1, sizeof(int) * 5);
  printf("capacity of ptr2 is: %ld\n", sizeof(ptr2)/sizeof(int) );



  return 0;
}

我在终端执行的操作

gcc -std=c99 tmp.c -o tmp
./tmp

终端输出

capacity of ptr1 is: 2
capacity of ptr2 is: 2

无论我为 malloc() 和 realloc() 输入什么容量参数,我都会得到这个输出

【问题讨论】:

  • sizeof(ptr2) 不会给你分配内存的容量。它给你的只是int 指针的大小,它保持不变。
  • sizeof 指针是实际指针的大小,而不是它可能指向的大小。当您在 C 中进行动态分配时,您必须自己跟踪“大小”。
  • sizeof array / sizeof *array 仅适用于 Arrays,并且仅适用于声明它们的 范围int *ptr1 声明了一个指针,所以 sizeof ptr1sizeof (a_pointer)(x86_64 上通常是 8 字节),sizeof (int)4。无论您为sizeof ptr1 / sizeof (int) 分配多少int,在x86_64 上都将是2
  • 使用搜索引擎。如果最频繁的重复,它就是一个

标签: c malloc dynamic-memory-allocation sizeof


【解决方案1】:

两件事:

  1. Arrays are not pointers, and vice-versa
  2. 无论如何,您没有检查分配内存的大小。

详细地说,这里的问题是,sizeof(ptr1) 不会产生指针指向的有效内存的大小,它返回指针本身的大小。指针(或任何类型,就此而言)的大小是恒定的。

对于分配器函数返回的指针,有一种直接的方法可以从指针本身获取请求(和分配)的内存大小,您需要自己跟踪大小。

也就是说:Please see this discussion on why not to cast the return value of malloc() and family in C..

【讨论】:

  • 最常见的重复之一
【解决方案2】:

您获取指针(不是数组)的大小,通常为 64 位,然后将其除以 int 的大小,通常为 32 位。这就是为什么你得到 2 作为结果。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-01
    • 2020-08-16
    • 1970-01-01
    • 2019-10-18
    • 1970-01-01
    • 2016-10-27
    • 1970-01-01
    • 2017-01-16
    相关资源
    最近更新 更多