0

Is there a way to determine the size of a char[] buffer via a char* pointer in C++? I'm using C++98.

The following lines of code all print out '8' (essentially sizeof(char*)). However I'm looking for the actual size of the buffer.

int maxBufferLen = 24;
char* buffer = new char[maxBufferLen];

std::cout << sizeof(buffer) << std::endl; // prints '8'
std::cout << ( sizeof(buffer) / sizeof(buffer[0]) ) << std::endl; // prints '8'

In practice, I am passing that char* buffer in between functions and I will not have access to the maxBufferLen variable that I am using to initialize it. As such, I'll need to determine the length using another way.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Walklikeapenguin
  • 127
  • 2
  • 10
  • 2
    Sorry, this is not possible. C++ does not work this way. You must track the size of all dynamically-allocated arrays yourself, by storing each one's explicit size, in some form or fashion, somewhere. – Sam Varshavchik Jul 16 '20 at 01:01
  • 2
    This is why classes like `std::vector`, and `std::string` exists. Without them, you have to keep track of all of those sizes. – PaulMcKenzie Jul 16 '20 at 01:02
  • If you start with `struct mybuf { char* buffer; size_t size; };` and add a "few" member functions and free functions to go with it, you're home: [`std::string`](https://en.cppreference.com/w/cpp/string/basic_string). – Ted Lyngmo Jul 16 '20 at 01:12
  • 1
    You're not getting `sizeof(char)`, that by definition is `1`. You're getting `sizeof(char*)` or the size of a pointer. – Mark Ransom Jul 16 '20 at 01:20

1 Answers1

5

There is general no way of determining the size of an array based on a pointer to an element of that array.

Here are typical ways to find out the size:

  • Store the size in a variable
    • A variant of this is to store both the pointer and the size (or alternatively, pointer past the end) as members of a class. An example of this approach is the std::span class template (this standard class is not in C++98, but you can write your own, limited version).
      • A variant this, which is generally used when the array is allocated dynamically (such as in your example), is to deallocate the memory in the destructor of the class and conforming to the RAII idiom. Examples of this approach are std::string and std::vector.
  • Or choose certain element value to represent the last element of the array. When iterating the array, encountering this "terminator" element tells you that the end has been reached. This is typically used with character strings, especially in C interfaces, where the null terminator character ('\0') is used.
eerorika
  • 232,697
  • 12
  • 197
  • 326