[Qt-interest] QString to char array

Jonathan Kew jonathan_kew at sil.org
Mon Dec 29 11:43:54 CET 2008


On 29 Dec 2008, at 06:43, Robin Helgelin wrote:

> On Mon, Dec 29, 2008 at 05:31, Avishek_Sharma <Avishek_Sharma at satyam.com 
> > wrote:
>> Hi,
>>   I came across this piece of code to convert/copy from QString to  
>> char array.
>>
>>    char arr[255];
>>    QString str;
>>     strcpy(arr,str.toAscii().constData());
>>
>> will this code work?
>
> Yes, it works, but your example is a dangerous when you are copying to
> a fixed sized array, better use strncpy in such cases.

You'll also have trouble if the QString contains non-Western  
characters. See under QString::toLatin1(), which tells us "The  
returned byte array is undefined if the string contains non-Latin1  
characters." Users don't usually appreciate apps that behave in  
"undefined" ways!

You should probably be using UTF-8 if you really need to put this into  
an array of 8-bit chars. But first you may need to read up about  
Unicode and other character encodings, and make sure you know what  
encodings are expected by whatever APIs you're using.

JK




More information about the Qt-interest-old mailing list