c++pointersvectormemory-management

How does vector<string>(const char** first, const char** last...) work when last is given simply as first plus string count?


I was looking into converting a raw const char** to a vector and discovered a concise answer here. This works, but I am confused as to how. The vector constructor usage is as follows:

const char* array[] = {"cat", "cows", "crows"};
int count = 3;
vector<string> stringVector(array, array + count);

I assume this is the

template< class InputIt >
vector( InputIt first, InputIt last,
  const Allocator& alloc = Allocator() );

vector constructor form from the docs using a std::string allocator, but how can the pointer arithmetic array + count give us the pointer to the last character string without taking the length of the interim character strings into account? Assuming the character string lengths are taken into account, how/where does this occur?

I would surmise that some 'measuring until null terminator is encountered' was happening under the hood if the params were starting pointer and string count alone, but this form appears to be using direct pointer arithmetic; array + count doesn't seem like it would have enough information to find the actual final character string starting address (unless operator+ has some very fancy footwork for character strings somehow).


Solution

  • You don't need to take the lengths of the strings into account. array is an array of pointers, not a 2-dimensional array of characters. array+count is a pointer past the end of the array, equivalent to &array[count].

    Note that it would still work if it were a 2-d array, e.g.

    #define MAXLENGTH 10
    const char array[][MAXLENGTH] = {"cat", "cows", "crows"};
    

    In this case, the size of each element is 10 bytes (the strings will be padded with null bytes), and the pointer arithmetic array + count would multiply by this.