Results 1 to 11 of 11

Thread: String initialization issue

Threaded View

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

    Default Re: String initialization issue

    you must not put such stuff in headers;

    header:
    Qt Code:
    1. enum { CONNECTIONS_AMOUNT=2 };
    2. extern const char *DB[CONNECTIONS_AMOUNT];
    3. extern const char *USERNAME[CONNECTIONS_AMOUNT];
    To copy to clipboard, switch view to plain text mode 

    .c-file
    Qt Code:
    1. const char *DB[CONNECTIONS_AMOUNT] = {"db1","db2"};
    2. const char *USERNAME[CONNECTIONS_AMOUNT] = {"root1","root2"};
    3. const char *PASSWORD[CONNECTIONS_AMOUNT] = {"admin","admin"};
    To copy to clipboard, switch view to plain text mode 

    otherwise you get one instance per file where the .h file is included - unless the linker can sort out the duplicates.


    To your question:
    you defined a big "rectangle" of x*y bytes.
    I define a vector of pointers to strings.
    This is not the same (in memory), but if you actually want an array of strings, perhaps closer to your intentions.
    Also, note that
    Qt Code:
    1. const char PASSWORD[CONNECTIONS_AMOUNT][MAX_STRING_SIZE]
    To copy to clipboard, switch view to plain text mode 
    allocates CONNECTIONS_AMOUNT * MAX_STRING_SIZE bytes.
    My code "allocates" (needs) CONNECTIONS_AMOUNT * sizeof(pointer) + the actually needed string sizes.

    Finally, your code could allow the strings to be modified (without const), mine cannot, as "somestring" is of type const char*.

    HTH

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

    Raccoon29 (22nd July 2008)

Similar Threads

  1. Reading from sockets in a multithreaded program
    By KoosKoets in forum Qt Programming
    Replies: 9
    Last Post: 4th April 2007, 20:43
  2. saving a c string of variable length in a shared memory?
    By nass in forum General Programming
    Replies: 4
    Last Post: 3rd January 2007, 14:40

Tags for this Thread

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.