user2410243
user2410243

Reputation: 187

String array length printed instead of the Number of Array Items in C++

I tried this declaration of array and check the size:

string path1[1] = {"D:\\Users\\user-pc\\Desktop\\testing\\inputs\\xml_source_example.xml"};
cout << path1->length();

and checked the size:

62

I wanted the output to be 1, so I tried with ->size() and I still got 62. I know that the first item in the array has length of 62, but I want the number of items in the array.

How can I get how many items there are in the array?

Upvotes: 0

Views: 172

Answers (5)

juanchopanza
juanchopanza

Reputation: 227370

Try this, leveraging std::begin and std::end:

std::end(path1) - std::begin(path1);

Alternatively, you can role out your own array size function:

#include <cstddef> // for std::size_t

template <typename T, std::size_t N>
constexpr std::size_t size(const T(&)[N])
{
  return N;
}

Usage:

#include <iostream>

int main()
{
  int a[42];
  std::cout << size(a) << std::endl;
}

Upvotes: 3

barak manos
barak manos

Reputation: 30136

For any statically allocated array in C/C++, use sizeof(array)/sizeof(*array) in order to get the number of entries.

Note #1:

The calculation will be made during compilation (and not during runtime).

Note #2:

int array[10]; // Static allocation
int array[] = new int[10]; // Dynamic allocation

Note #3:

You can apply this method only in the scope of declaration.

For example, if array is declared inside a function, then you can apply this method only in the scope of that function. You cannot apply this method inside any other function which receives array as an argument, because it is regarded as a pointer within that function.

If the array is declared globally in a source file, then you can apply this method in all functions within that file.

Upvotes: 1

Vinayak Pingale
Vinayak Pingale

Reputation: 1315

Try using

string path1[1] = "D:\\Users\\user-pc\\Desktop\\testing\\inputs\\
xml_source_example.xml";
cout << sizeof(path1)/sizeof(path1[0]);

This will work as per your requirement but when pointer will come it will fail. But as per your requirement, this will suffice.

Upvotes: 0

Davidbrcz
Davidbrcz

Reputation: 2397

There are several solutions. 2 have already been given by juanchopanza and barak manos. Here is the third one

#include <type_traits>

int a[12];
std::cout<<std::extent<decltype(a)>::value<<std::endl;

But consider using std::array instead of old-C syle array.

Upvotes: 0

Joe
Joe

Reputation: 428

In c++,arrays aren't managed for you, and will always be the length set at declaration. There are many types of containers which are managed in the STL. I wouldn't hesitate to try out Vectors, if I had to make a reccomendation but have a look see if any of the others fit your needs better.

Upvotes: 1

Related Questions