-4

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++) {..
user3298017
  • 31
  • 1
  • 6

2 Answers2

5

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!

Marco
  • 7,007
  • 2
  • 19
  • 49
0
size_t length = sizeof(array) / sizeof(array[0]);
Marco
  • 7,007
  • 2
  • 19
  • 49
lychee
  • 1,771
  • 3
  • 21
  • 31