tags:

views:

157

answers:

3

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..

Thankss..

+1  A: 
int len=sizeof(array)/sizeof(int);

Should work.

Paul
No - in many cases this will *not* work.
Paul R
It works, however `site_t len = sizeof(array)/sizeof(array[0]);` it's a bit better (i.e. it still works when datatype of array elements has been changed.
Grzegorz Gierlik
@Grzegorz: Show us how it works for this array: `void f(int array[]) { site_t len = sizeof(array)/sizeof(array[0]); }`
sbi
@Paul R: Why not? Unless `array` is an incomplete type (one case); if it's an array of `int` this will work.
Charles Bailey
@sbi: The poorly named `array` parameter is actually a pointer.
caf
@caf: Yes, and that is something beginners keep running into. (I suppose a question like this _is_ from a beginner.)
sbi
@Charles: see sbi's answer as to why this only works for certain cases.
Paul R
I didn't see sbi's first comment when I wrote mine. Yes, in C99 variable length arrays are a second case. Obviously if `array` isn't an array but is actually a pointer then it's not going to work but there was no indication that this might be the case in the answer.
Charles Bailey
+13  A: 

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 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.

sbi
A: 

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.