6

What is the quickest way to find the number of elements in a static array and dynamic array?

webgenius
  • 856
  • 3
  • 13
  • 30
  • Possible duplicate: http://stackoverflow.com/questions/851716/count-repeated-elements-in-an-array-in-c – Tim Post Apr 05 '10 at 09:40
  • 1
    Possible duplicate: http://stackoverflow.com/questions/2347766/how-many-elements-are-full-in-a-c-array – Tim Post Apr 05 '10 at 09:41

1 Answers1

10

There is no way of finding the number of elements in a dynamically created array. For a non-dynamic array, you can use sizeof(array)/sizeof(type). However, this is not as useful as it seems:

void f( int a[] ) {
   // sizeof(a) will be the size of a pointer, probably 4
}

int main() {
     int a[100];
     // sizeof(a)/sizeof(int) will be 100
     f( a );
}

This is because arrays decay into pointers when passed to functions. So in both cases, you probably need to remember the size of the array and pass it to functions as a separate parameter. So a function to sum an array (for example) would look like this:

int sum( int a[], int n ) {
    int total = 0, i;    
    for ( i = 0; i < n; i++ ) {
        total += a[i];
    }
    return total;
}
  • 6
    Typically one would use 'sizeof(array)/sizeof(array[0])'. Additionally there may be non-standard, non-portable ways to find the number of elements in a dynamic array, but it's best to store the size separately on creation and pass it to anything that needs to know the size. – Dan Olson Apr 05 '10 at 09:42
  • 1
    @Georg Please do not edit the technical content of my answers - I have written the code I posted quite consciously. If you think it can be improved, make a comment or post an answer of your own. –  Apr 05 '10 at 19:42