首页 > 解决方案 > 如何确定 C 中动态分配数组的大小?

问题描述

我有一个结构,我需要一个数组。我必须将该数组作为参数传递并迭代该数组。那么,如何确定函数中数组的大小呢?我知道我们可以将大小作为另一个参数传递,但我试图避免传递第二个参数。先感谢您。

这是代码:

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

typedef struct {
    int weight;
    int profit;
}Object;

void IterateArray(Object *objects) {
    int size = sizeof(objects) / sizeof(objects[0]);
    printf("Size: %d", size);
    //for (int i = 0; i < size; i++) {
    //}
}

void main() {
    int n = 5;
    //Object objects[n];                // Can't run this
    Object *objects = (Object*)calloc(n, sizeof(Object));
    printf("Size of objects: %d\n", sizeof(objects));
    printf("Size of objects[0]: %d\n", sizeof(objects[0]));
    IterateArray(objects);
}

对于上面的代码,我得到以下输出。

Size of objects: 4
Size of objects[0]: 8
Size: 0

标签: arrayscdynamic-memory-allocationcalloc

解决方案


推荐阅读