Igbe Chukwudi
Igbe Chukwudi

Reputation: 83

how to find the number of elements in an array

I have an int array and I need to find the number of elements in it. I know it has something to do with sizeof but I'm not sure how to use it exactly. example

 int data2[]={a,b,c,d};

Upvotes: 3

Views: 398

Answers (1)

pb2q
pb2q

Reputation: 59637

With an array you can do:

int numElements = sizeof(data) / sizeof(data[0]);

But this only works with arrays, and won't work if you've passed the array to a function: at that point the array decays to a pointer, and so sizeof will return the size of the pointer.

You'll see this wrapped up in a macro:

#define ARRAY_LENGTH(x) (sizeof (x) / sizeof (x)[0])

Upvotes: 7

Related Questions