How to find the size of integer array

前端 未结 4 1113
执笔经年
执笔经年 2020-12-07 18:53

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.

相关标签:
4条回答
  • 2020-12-07 19:31

    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.

    0 讨论(0)
  • 2020-12-07 19:45

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

    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.

    0 讨论(0)
  • 2020-12-07 19:49

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

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

    0 讨论(0)
  • 2020-12-07 19:49
    int len=sizeof(array)/sizeof(int);
    

    Should work.

    0 讨论(0)
提交回复
热议问题