如何找到整数数组的大小 [英] How to find the size of integer array

查看:25
本文介绍了如何找到整数数组的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 C 中找到整数数组的大小.

How to find the size of an integer array in C.

无需遍历整个数组一次即可找到数组大小的任何方法.

Any method available without traversing the whole array once, to find out the size of the array.

推荐答案

如果数组是全局、静态或自动变量 (int array[10];),则 sizeof(array)/sizeof(array[0]) 有效.

If the array is a global, static, or automatic variable (int array[10];), then sizeof(array)/sizeof(array[0]) works.

如果是动态分配的数组 (int* array = malloc(sizeof(int)*10);) 或作为函数参数传递 (void f(int array[])),那么在运行时就找不到它的大小.您必须将尺寸存储在某处.
请注意,即使对于第二种情况,sizeof(array)/sizeof(array[0]) 也能很好地编译,但它会默默地产生错误的结果.

If it is a dynamically allocated array (int* array = malloc(sizeof(int)*10);) or passed as a function argument (void f(int array[])), then you cannot find its size at run-time. You will have to store the size somewhere.
Note that sizeof(array)/sizeof(array[0]) compiles just fine even for the second case, but it will silently produce the wrong result.

这篇关于如何找到整数数组的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆