如何找到动态数组的大小

How to find the size of dynamic array

有什么方法可以找到在这段代码

中为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;
    }

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

是的,通过将大小保存在变量中:

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

    size_t size = rand() % 11;
    if(size == 0)
    {
        fprintf(stderr, "Size 0, no point in allocating memory\n");
        return 1;
    }

    RandomArray = malloc(size * sizeof *RandomArray)
    if(RandomArray == NULL)
    {
        fprintf(stderr, "no memory left\n");
        return 1;
    }
    printf("%zu  %zu\n", sizeof(RandomArray), size);

    // don't forget to free the memory
    free(RandomArray);

    return 0;
}

注意 sizeof(RandomArray) returns 你指向 int 的指针的大小 需要存入内存,而sizeof(*RandomArray)returns你的大小 一个 int.

另外别忘了释放内存。

由于表达式 *RandomArray 的类型为 int,因此 sizeof(*RandomArray) 的计算结果为 sizeof(int)。它不会告诉您分配了多少内存。

动态分配内存时,您需要跟踪自己分配了多少内存。在上述情况下,您需要将随机数存储在某处,以便您知道该数量是多少。

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

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

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

  • 打印 sizeof return 应该使用 %zu 格式说明符来完成。它returns 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.
  • malloc 可能 return NULL 当你将 0 传递给它时。单独处理这种情况。如果你得到 sz!=0 并在 RandomArray 中得到 NULL 抛出错误。

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

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

sizeof(RandomArray) 总是得到 4 个字节(等于指针大小),如果你想找到为 RandomArray

分配了多少字节
/* Since its implimentation dependent, so I'm not 
  advising you to access RandomArray[-1], also proper type casting needed */
printf("memory allocated = %d \n",RandomArray[-1]);

来自

The C programming language by Denis Ritchie & Kernighan

 typedef long Align;    /* for alignment to long boundary */
   union header {         /* block header */
       struct {
           union header *ptr; /* next block if on free list */
           unsigned size;     /* size of this block */
       } s;
       Align x;           /* force alignment of blocks */
   };
   typedef union header Header;

从未使用 Align 字段;它只是强制每个 header 在 worst-case 边界 上对齐。 在malloc中,请求的字符大小被四舍五入到适当的header-sized个单位;将分配的块包含 header本身多了一个单位,也就是记录在 size header 的字段。 malloc 返回的指针指向空闲 space,而不是 header 本身

              RandomArray[-1]                      
   -----------------------------------------
   |        |     SIZE     |               |
   -----------------------------------------
                                          RandomArray

        -> a block returned by malloc 

sizeof运算符在编译时工作,操作数为可变长度数组且动态内存分配为的情况除外运行次次操作。 在表达式中:

printf("%d  %d",sizeof(RandomArray),sizeof(*RandomArray));

RandomArray的类型是int **RandomArray的类型是int

因此,表达式等同于:

printf("%d  %d",sizeof(int *),sizeof(int));

sizeof 将产生整数常量的结果,因此,无论分配给 RandomArray.[=28= 的内存大小如何,每次都会得到相同的结果]

How to find the size of dynamic array

从动态分配内存的位置开始跟踪 大小


请注意,您在分配内存时将 return 乘以 rand()%11 的值乘以 sizeof *RandomArray,并且 rand() 可能 return 0 也将导致 malloc(0)。很高兴知道(来自 C Standards#7.22.3):

....If the size of the space requested is zero, the behavior is implementation-defined: either a null pointer is returned, or the behavior is as if the size were some nonzero value, except that the returned pointer shall not be used to access an object.