Ask coding questions

← Back to all posts
Array Size in C++
ferweja (0)

Does C++ in Repl.it have a function that gives the size of an array?

Background: Other implementations of C++ have a length or size function that gives the number of elements in an array.

Example: if an array called "sample" is declared, the number of elements could be given by "sample.size()" or "sample.length()" or "_countof(sample)".

This is especially useful when passing arrays for processing in a function; the size would not have to be passed as a parameter.

I haven't been able to find something that works in Repl.it.

Thanks!

Comments
hotnewtop
Coder100 (16850)

no. Arrays don't have a length.

Use a vector:

#include <vector>

std::vector<int> a = {1,2,3};

a.size(); // 3

not only is it the more idiomatic way, it actually has a real length!

InvisibleOne (2677)

I believe it is something like this:

int count = sizeof(my_array)/sizeof(my_array[0]);

This might also help: https://stackoverflow.com/questions/4839626/element-count-of-an-array-in-c

ferweja (0)

@InvisibleOne Thanks!! That will work!