C语言 如何找到整数数组的大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2773328/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 05:22:46  来源:igfitidea点击:

How to find the size of integer array

carrays

提问by AGeek

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

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

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

无需遍历整个数组一次即可使用的任何方法,以找出数组的大小。

回答by sbi

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

如果数组是全局、静态或自动变量 ( int array[10];),则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.

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

回答by user333453

If array is static allocated:

如果数组是静态分配的:

size_t size = sizeof(arr) / sizeof(int);

if array is dynamic allocated(heap):

如果数组是动态分配的(堆):

int *arr = malloc(sizeof(int) * size);

where variable size is a dimension of the arr.

其中可变大小是 arr 的维度。

回答by Noobay

_msize(array)in Windows or malloc_usable_size(array)in Linux should work for the dynamic array

_msize(array)在 Windows 或malloc_usable_size(array)Linux 中应该适用于动态数组

Both are located within malloc.h and both return a size_t

两者都位于 malloc.h 中并且都返回一个 size_t

回答by Paul

int len=sizeof(array)/sizeof(int);

Should work.

应该管用。