PDA

View Full Version : convert from QString to char[sizeof(...)]



adamatic
3rd February 2009, 07:46
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/faqs/faq.2007-01-30.9032238253/

Thank you.

caduel
3rd February 2009, 10:28
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.


QString string;
// 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 not 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:

some_c_api(... string.toLatin1().constData(), ...);

However, this would be very bad


const char* msg = string.toLatin1().constData();
some_c_api(... msg, ...); // msg is dangling pointer now!

HTH

adamatic
3rd February 2009, 11:15
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.

hickscorp
2nd September 2011, 14:50
Bump. i'm confused about something.


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:
QByteArray arr = theString.toLatin1();
some_c_api(arr.constData());

Isn't it risked to do the first method?

Thanks,
Pierre.

ChrisW67
3rd September 2011, 09:05
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:


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