HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcppCritical

How do I find the length of an array?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
arrayhowfindthelength

Problem

Is there a way to find how many values an array has? Detecting whether or not I've reached the end of an array would also work.

Solution

If you mean a C-style array, then you can do something like:

int a[7];
std::cout << "Length of array = " << (sizeof(a)/sizeof(*a)) << std::endl;


This doesn't work on pointers (i.e. it won't work for either of the following):

int *p = new int[7];
std::cout << "Length of array = " << (sizeof(p)/sizeof(*p)) << std::endl;


or:

void func(int *p)
{
    std::cout << "Length of array = " << (sizeof(p)/sizeof(*p)) << std::endl;
}

int a[7];
func(a);


In C++, if you want this kind of behavior, then you should be using a container class; probably std::vector.

Code Snippets

int a[7];
std::cout << "Length of array = " << (sizeof(a)/sizeof(*a)) << std::endl;
int *p = new int[7];
std::cout << "Length of array = " << (sizeof(p)/sizeof(*p)) << std::endl;
void func(int *p)
{
    std::cout << "Length of array = " << (sizeof(p)/sizeof(*p)) << std::endl;
}

int a[7];
func(a);

Context

Stack Overflow Q#4108313, score: 660

Revisions (0)

No revisions yet.