arrays - 如何确定 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
解决方案
推荐阅读
- python - databricks dbfs 是否支持文件元数据,例如文件/文件夹创建日期或修改日期
- nightwatch - 如何在博客或网站中应用黑暗或夜间模式?
- c# - 如何在 C# 中将文本框值带到 MapWinGIS axMap1.Latitude 函数
- python - 来自 3 个字典列表的值的 SUM 和 GROUP ing
- d3.js - 缩放/平移应该从新位置工作,而不是跳回到以前的位置
- java - 如何在 Android 中以编程方式设置自动启动权限?
- java - 使用 RestTemplate 时如何映射 ResponseEntity 中的响应对象?
- java - 致命异常:java.lang.AssertionError - 在 kayako messenger 支持工具中
- css - 为body设置背景颜色时,为什么body margin不会导致白色边框?
- jenkins - 部署到另一台服务器时如何在 Jenkins Pipeline 中传递 ssh 凭据