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.

4
  • 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. Commented Jul 16, 2020 at 1: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. Commented Jul 16, 2020 at 1: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. Commented Jul 16, 2020 at 1:12
  • 1
    You're not getting sizeof(char), that by definition is 1. You're getting sizeof(char*) or the size of a pointer. Commented Jul 16, 2020 at 1:20

1 Answer 1

6

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.
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.