Results 1 to 5 of 5

Thread: convert from QString to char[sizeof(...)]

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #2
    Join Date
    Dec 2006
    Posts
    849
    Qt products
    Qt4
    Platforms
    Unix/X11
    Thanks
    6
    Thanked 163 Times in 151 Posts

    Default 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.

    Qt Code:
    1. QString string;
    2. // make sure we do not overwrite "msg" (ie prevent writing more bytes than the buffer can accomodate)
    3. // (there are more elaborate ways to do that)
    4. // note esp. that strncpy does [B]not[/B] guarantee the result to be 0-terminated when the input is too large!
    5. strncpy(msg, string.toLatin1().constData(), sizeof(msg));
    6. // therefore, often one does
    7. msg[sizeof(msg)-1]=0;
    To copy to clipboard, switch view to plain text mode 

    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:
    Qt Code:
    1. some_c_api(... string.toLatin1().constData(), ...);
    To copy to clipboard, switch view to plain text mode 

    However, this would be very bad
    Qt Code:
    1. const char* msg = string.toLatin1().constData();
    2. some_c_api(... msg, ...); // msg is dangling pointer now!
    To copy to clipboard, switch view to plain text mode 
    HTH

  2. The following user says thank you to caduel for this useful post:

    adamatic (3rd February 2009)

Similar Threads

  1. convert QString to QByteArray
    By morgana in forum Qt Programming
    Replies: 5
    Last Post: 2nd March 2011, 13:33
  2. Read binary file and convert to QString
    By jaca in forum Qt Programming
    Replies: 12
    Last Post: 13th June 2008, 23:05
  3. convert QString to int
    By mattia in forum Newbie
    Replies: 2
    Last Post: 4th January 2008, 09:10
  4. how to convert int to QString?
    By phillip_Qt in forum Newbie
    Replies: 2
    Last Post: 5th October 2007, 08:07
  5. Convert from iso-8859-1 to... Something else :-)
    By Nyphel in forum Qt Programming
    Replies: 4
    Last Post: 7th March 2007, 17:59

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Qt is a trademark of The Qt Company.