1

I am new to c++, so please do not judge me strictly. I am trying to get size of array, but this code sample always returns 2. Also I can use only C++11. What is the problem and how can I deal with it? Thank you in advance.

String string = "paris";
char * array = new char [string.length() + 1];
int arraySize = sizeof(array) / sizeof(array[0]);
Max
  • 21
  • 4

2 Answers2

1

It returns 2 because array is a pointer , meaning sizeof(array) returns the size of the pointer, not the array. You have 16-bit pointers?

sizeof(array) / sizeof(array[0]); only works for compile-time arrays.

Solution is to use std::vector or std::array.

Also use std::size_t for lengths, not int.

Quimby
  • 17,735
  • 4
  • 35
  • 55
1

You can't find out the size of an array that was created using the keyword new(the way you did). The size of an array allocated using new[] is not stored in any way in which it can be accessed later.

You should instead use std::vector which stores the length for you.

std::string string = "paris";
std::vector<char> myVec(string.length() + 1); //creates vector of size string.length() + 1
int arraySize = myVec.size();

Jason
  • 36,170
  • 5
  • 26
  • 60