Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Struct Array Initialization and String Literals

Tags:

c++

Is following array initialization correct? I guess it is, but i'm not really sure if i can use const char* or if i better should use std::string. Beside the first question, do the char pointers point to memory segments of same sizes?

struct qinfo
{
    const char* name;
    int nr;
};
qinfo queues[] = {
    {"QALARM", 1},
    {"QTESTLONGNAME", 2},
    {"QTEST2", 3},
    {"QIEC", 4}
};
like image 245
Christian Ammer Avatar asked May 05 '10 07:05

Christian Ammer


4 Answers

Yes, that looks fine. Obviously you won't be able to subsequently modify any of the name strings (although you can change the pointers to point at different strings if you need to). Storage for each of the const strings will be only as much as is needed and will typically be read-only.

like image 101
Paul R Avatar answered Nov 07 '22 09:11

Paul R


The initialization is fine but the char* will point to different sized memory chunks as they need to hold strings of different lengths. For your other question, if you want to ensure that the string pointed to by the struct member remains the same after initialization, you should use const std::string (I am ignoring cast hacks here). To do the same you with a char pointer, you would need to declare it as

 const char* const 

i.e. both the value pointer and the value pointed to are const.

like image 26
Jasmeet Avatar answered Nov 07 '22 09:11

Jasmeet


Looks fine, the memory sizes for the strings will be different as arrays of char* initialized like that will be allocated different sizes. The compiler will allocate just enough spaces to contain the characters then an additional "\0" to terminate the string.

like image 2
shuttle87 Avatar answered Nov 07 '22 09:11

shuttle87


It's ok since string literals has static storage duration. No need to use std::string in this case because it will involve dynamic memory allocation at runtime.

like image 1
Kirill V. Lyadvinsky Avatar answered Nov 07 '22 09:11

Kirill V. Lyadvinsky