Reputation: 3932
I want to concat an integer with wchar_t, tried below method but its crashing
const wchar_t mySalvo[10] = L"Group:"; // THis is global
int salvo = 0;
wchar_t buffer[1] = L"\n";
itoa(salvo, buffer, 1);
wcscat(mySalvo, buffer); // app crashes here
ITs in C
Upvotes: 0
Views: 411
Reputation: 20028
There are numerous issues with this code:
const wchar_t mySalvo[10] = L"Group:"; // THis is global
int salvo = 0;
wchar_t buffer[1] = L"\n";
itoa(salvo, buffer, 1);
wcscat(mySalvo, buffer); // app crashes here
wcscat
(your compiler surely gave you a warning??).wchar_t
elements, so even if it weren't read-only, it would only be long enough to store a 3 digit number.itoa
is the number base, which would normally be 10. It is meaningless to have a number of base 1.wcscat
to write into a constant string, which is verboten, even assuming it were long enough.So there's a lot of fundamentals here you need to come to terms with. String allocation, memory initialisation, arrays, constant variables and constant literals, and more.
What you are trying to do is simply produce a formatted string. The sprintf
family of string formatting functions provide all you could possibly need, plus a secure way of doing it.
The simplest solution would be something like this:
void show_message(unsigned salvo)
{
wchar_t message[64];
swprintf_s(message, sizeof(message), L"Group: %u\n", salvo);
// do something with message!
}
So if you called show_message(123)
, the resulting value in message
would be: "Group: 123\n"
.
Upvotes: 1
Reputation: 67556
mySalvo is const - which was spotted by Chris.
And on top of it
wchar_t buffer[1] = L"\n";
itoa(salvo, buffer, 1); -
wcscat(mySalvo, buffer); // app crashes here
it is undefined behavior asd you do not have enough space to accommodate L"\n"
. Both calls invoke the UB. itoa
will not work with the wchar_t strings. You need to find the appropriate function.
try wchar_t buffer[2] = L"\n";
instead
Upvotes: 0