1

What I am trying to do is to save multiple different pointers to unique wchar_t strings into a vector. My current code is this:

std::vector<wchar_t*> vectorOfStrings;
wchar_t* bufferForStrings;

for (i = 0, i > some_source.length; i++) {
    // copy some string to the buffer...

    vectorOfStrings.push_back(bufferForStrings);
}

This results in bufferForStrings being added to the vector again and again, which is not what I want.

RESULT:

[0]: (pointer to buffer)
[1]: (pointer to buffer)
...

What I want is this:

[0]: (pointer to unique string)
[1]: (pointer to other unique string)
...

From what I know about this type of string, the pointer points to the beginning of an array of characters which ends in a null terminator.

So, the current code effectively results in the same string being copied to the buffer again and again. How do I fix this?

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83

1 Answers1

0

The simplest way is to use std:wstring, provided by the STL, as the type for your vector's elements. You can use the constructor that class provides to implicitly copy the contents of your wchar_t*-pointed buffer to the vector (in the push_back() call).

Here's a short demo:

#include <string>
#include <vector>
#include <iostream>

int main()
{
    wchar_t test[][8] = { L"first", L"second", L"third", L"fourth" };
    std::vector<std::wstring> vectorOfStrings;
    wchar_t* bufferForStrings;
    size_t i, length = 4;
    for (i = 0; i < length; i++) {
        // copy some string to the buffer...
        bufferForStrings = test[i];
        vectorOfStrings.push_back(bufferForStrings);
    }

    for (auto s : vectorOfStrings) {
        std::wcout << s << std::endl;
    }

    return 0;
}

Further, if you later need access to the vector's elements as wchar_t* pointers, you can use each element's c_str() member function to retrieve such a pointer (though that will be const qualified).

There are other methods, if you want to avoid using the std::wstring class; for 'ordinary' char* buffers, you could use the strdup() function to create a copy of the current buffer, and send that to push_back(). Unfortunately, the equivalent wcsdup() function is not (yet) part of the standard library (though Microsoft and others have implemented it).

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83