4

I have tried wcscat() but i get a runtime access violation.

wchar_t* a = L"aaa";
wchar_t* b = L"bbb";
wchar_t* c;
c = wcscat(a, b);

Can somebody tell me what is wrong here? Or another way to solve my problem? Thanks

  • 3
    I just want to add, if you are using C++, this is the WRONG way to be doing things. The C++ standard library has string objects because of the difficulty with c-strings. – rlbond May 08 '09 at 23:52

3 Answers3

11

wcscat doesn't create a new string - it simply appends b to a. So, if you want to make sure you don't cause a runtime access violation, you need to make sure there's space for b at the end of a. In the case above:

wchar_t a[7] = L"aaa";
wchar_t b[]  = L"bbb";
wchar_t* c;
c = wcscat(a, b);

You can still get a return value from the function, but it will simply return a.

Samir Talwar
  • 14,220
  • 3
  • 41
  • 65
4

Use c++'s built in wstring:

#include <string>
using std::wstring;

int main()
{
    wstring a = L"aaa";
    wstring b = L"bbb";
    wstring c = a + b;
}

wcscat is for c-style strings, not c++ style strings. The c way to do this is

wchar_t* a = L"aaa";
wchar_t* b = L"bbb";
wchar_t c[7];
wcscpy(c, a);
wcscat(c, b);

EDIT: Wow, now that I edited it, it makes it look like I copied one of the answers below.

rlbond
  • 65,341
  • 56
  • 178
  • 228
1

The wcscat function appends the second argument onto the string buffer in the first argument. It looks as though this might be your first experience using strings in C. You could make your example work by doing the following:

wchar_t* a = L"aaa";
wchar_t* b = L"bbb";
wchar_t c[7];
wcscpy(c, a);
wcscat(c, b);

When using C string manipulation functions, you must ensure that you allocate enough buffer space for the string operation begin performed (the C runtime won't do it for you). In this case, it means the c buffer must contain enough space to hold the result string. I have precalculated that the result is 6 characters long plus the trailing null, which means I need to allocate 7 characters.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285