3

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}; 

1 Answer 1

7

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]) 
Sign up to request clarification or add additional context in comments.

2 Comments

+1. It's a good idea to stick this in a macro, since if you copy and paste it to use it on a different array you can forget to change one of the occurrences of data: #define lengthof(x) (sizeof (x) / sizeof (x)[0])
@j_random_hacker I call that ARRAY_LENGTH since that's the only thing it can take the length of.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.