-1

I have a function that receive a wchar_t* parameter named somestring.

I'd like to resize wchar_t* somestring to contain more elements than it is passed, bBecause I want to copy something larger than the original string:

void a_function(wchar_t *somestring) {
    // I'd like the somestring could contain the following string:
    somestring = L"0123456789"; // this doesn't work bebause it's another pointer
}

int _tmain(int argc, _TCHAR* argv[])
{
    wchar_t *somestring = L"0123";
    a_function(somestring);
    // now I'd like the somestring could have another string at the same somestring variable, it should have the following characters: "0123456789"
}

Is it possible to resize wchar_t *somestring to contain more characters?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
felipe
  • 1,212
  • 1
  • 15
  • 27
  • You tagged this with both C and C++, but they are wildly different languages now despite their common heritage - so is this a C or a C++ question? – Dai May 12 '17 at 21:14
  • Also, don't use `TCHAR`: http://stackoverflow.com/questions/234365/is-tchar-still-relevant – Dai May 12 '17 at 21:14
  • If c, you want to use `wcscpy`. If C++, you want to use `std::wstring` – Donnie May 12 '17 at 21:15
  • "the content of a `wchar_t *`" is the memory address of a `wchar`. Sure, you can change that address (i.e. make the pointer point somewhere else). I guess you mean to ask whether you can change the characters that are being pointed to. – M.M May 13 '17 at 00:19

1 Answers1

2

As you found out, void a_function(wchar_t *somestring) { somestring = L"0123456789";} just changes the local pointer variable somestring without any effect to the caller. Exchanging the caller`s pointer value requires to pass a pointer to this pointer:

void a_function(const wchar_t **somestring) {
  *somestring = L"0123456789";
}

int main(int argc, char* argv[]) {
    const wchar_t *somestring = L"0123";
    a_function(&somestring);
    // somestring now points to string literal L"0123456789";
}

Note that by overriding the pointer you loose the reference to string literal L"0123". Note further that the data type is now const wchar_t*, because otherwise one should not assign a string literal (modifying the content of a string literal is not allowed).

Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58
  • 1
    "*Exchanging the caller's pointer value requires to pass a pointer to this pointer*" - or, in C++, you can pass a reference instead: `void a_function(const wchar_t* &somestring) { somestring = L"0123456789"; }` ... `a_function(somestring);` – Remy Lebeau May 12 '17 at 23:54