c - 如何找到动态数组的大小

标签 c dynamic-memory-allocation

有什么方法可以找到在这段代码中为 RandomArray 分配了多少字节

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

    int main()
    {
    int *RandomArray;
    int n;
    srand(time(NULL));

    RandomArray=malloc(sizeof *RandomArray * (rand()%11));
    printf("%d  %d",sizeof(RandomArray),sizeof(*RandomArray));

    return 0;
    }

我也不知道上面的代码是否会有任何实际用途。但我是从编程的角度来看的。

最佳答案

啊,这是实验代码。那里有有趣的东西。

  • 您将为 N 个整数分配内存,其中 N 介于 010 之间,包括 0 10
  • 然后您将 sizeof 应用于指针 (int*) 及其指向的内容 (int)。分配多少内存并不重要。此行的输出将相同。

  • 这里没有错误检查。如果是,您无法确定它是否完全成功,因为 rand() 可能会给出 0 作为结果。您需要将它存储在某处并检查它是否为 0,因为在那种情况下 malloc 可能返回也可能不返回 NULL

  • 打印 sizeof 返回的内容应该使用 %zu 格式说明符来完成。它返回 size_t

  • To be more clear remember it is a pointer pointing to dynamically allocated memory. RandomArray is not an array - it is an pointer pointing to contiguous memory. That doesn't make it array. It is still a pointer. And the sizeof trick that you wanted to apply thinking RandomArray is an array won't work. In general we keep track of it - using some variable. But here you don't know how much memory you allocated.
    当您将 0 传递给
  • malloc 时,它可能会返回 NULL。单独处理这种情况。如果你得到 sz!=0 并在 RandomArray 中得到 NULL 抛出错误。

      size_t sz = rand()%11;
      RandomArray = malloc(sz);
      if(!RandomArray && sz){
         perror("malloc");
         exit(EXIT_FAILURE);
      }
    

在所有这些谈话之后 - 简短的回答是,使用此设置到目前为止没有使用代码(您编写的代码)。您不知道在 malloc 中的那个案例中 rand() 返回了什么。

关于c - 如何找到动态数组的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48958818/

相关文章:

ATMEGA328 的 c 库创建

c - SYSTEM 调用执行后的段错误

字符串常量之前预计出现 c 编程错误 ‘;’ 、 ‘,’ 或 ‘)’

c++ - 如何为嵌套指针结构动态分配内存?

c - Linux 串口 : Blocking Read with Timeout

c - 我如何检查这种宏依赖性?

c++ - QTableWidget 项的内存管理

c - 跟踪内存 malloc/free 的简单 C 实现?

c - libc 检测到 *** ./textfileread.exe : realloc(): invalid next size: 0x08643008

c - 在 C 中动态分配二维数组