-2

How can I get the length of an array in C, I tried it how i get it in other languages but it doesn't work like this:

int array [5]; for(int i = 0; i < array.length; i++) {.. 
2
  • Did you search it on Google? Commented Mar 11, 2015 at 15:58
  • 2
    @haccks nope he didn't Commented Mar 11, 2015 at 15:58

2 Answers 2

6

If its on the stack, you can use the sizeof operator to determine its raw byte size:

int array[5]; size_t array_size = sizeof(array); 

But this gives you the size in bytes, not the number of elements. However, you can calculate the number of elements with this approach:

int array[5]; size_t array_elems = sizeof(array) / sizeof(* array); 

If you array is a pointer (e.g. function call or dynamic memory allocation) then you have to keep track it yourself!

Sign up to request clarification or add additional context in comments.

Comments

0
size_t length = sizeof(array) / sizeof(array[0]); 

5 Comments

downvote for correct solution?
Not my downvote. This answer is the same as that from @d3l but without any explanation. A good answer should explain why it is an answer. A short piece of code may be correct but it does not educate the asker.
but size_t is typedef as unsigned long int
Maybe, but so can it be typedef'd as unsigned int ;) Its implementation defined.
Not my downvote, but a copy-pasted code snippet is not enough.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.