convert from QString to char[sizeof(...)]
Hello.
I want to convert from QString to char[sizeof(...)] and vice versa. I was checking some threads in the forum but I can convert to char* and not to char[sizeof(..)], I know is almost the same but when I write the following code:
QString string;
char msg[sizeof(SIZE)];
QByteArray ba = string.toLatin1();
const char *c_str2 = ba.data();
msg=(char*)c_str2;
I obtain this error: incompatible types in assignment of `char*' to `char[2]'
I can imagine that it is something basic but I dont know how to do it.
P.d. I need use [sizeof(..)] to assign a determinate memory space.
P.d. I was checking this thread to check how convet a QString to char* http://www.qtsoftware.com/developer/...30.9032238253/
Thank you.
Re: convert from QString to char[sizeof(...)]
char * is a pointer to some characters somewhere in your memory.
char[] is a block of memory containing characters.
Different concepts really.
If you want to "assign" the pointer to the block, you need to copy the block pointed to by the pointer: this is what strcpy (and strncpy) are for.
Code:
// make sure we do not overwrite "msg" (ie prevent writing more bytes than the buffer can accomodate)
// (there are more elaborate ways to do that)
// note esp. that strncpy does [B]not[/B] guarantee the result to be 0-terminated when the input is too large!
strncpy(msg, string.toLatin1().constData(), sizeof(msg));
// therefore, often one does
msg[sizeof(msg)-1]=0;
Note that if you need to pass a char* to a C-API you can just pass string.toLatin1().constData() ... the pointer will be til its surrounding expression has been evaluated:
Code:
some_c_api(... string.toLatin1().constData(), ...);
However, this would be very bad
Code:
const char* msg = string.toLatin1().constData();
some_c_api(... msg, ...); // msg is dangling pointer now!
HTH
Re: convert from QString to char[sizeof(...)]
ok, thank you.
I have used the strncpy function and it is working now. :D
I gave more space to the msg too becuase I was losing datas sometimes becuase the string it was bigger than the msg.
Regards.
Re: convert from QString to char[sizeof(...)]
Bump. i'm confused about something.
Quote:
Originally Posted by
caduel
Code:
some_c_api(... string.toLatin1().constData(), ...);
When passing the string.toLatin1().constData() to some_c_api, while inside some_c_api isn't the QByteArray generated by string.toLatin1() already destructed?
i myself do:
Code:
some_c_api(arr.constData());
Isn't it risked to do the first method?
Thanks,
Pierre.
Re: convert from QString to char[sizeof(...)]
The scope of temporary objects is the end of the statement (i.e. the semi-colon). The temporary QByteArray is valid until the end of the some_c_api() function call.
Something like this would be risky:
Code:
const char *s = theString.toLatin1().constData();
// the byte array disappears here but you are holding a pointer to some of its deallocated memory
some_c_api(s);
// potential boom