开发者

Struct Array Initialization and String Literals

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 n开发者_Python百科r;
};
qinfo queues[] = {
    {"QALARM", 1},
    {"QTESTLONGNAME", 2},
    {"QTEST2", 3},
    {"QIEC", 4}
};


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.


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.


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.


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.


Your code is fine, but the strings will be in different amounts of memory, which may be read-only.

To answer the rhetorical question, a minor adjustment to the struct will allow modification of the strings and fix the memory layout (still platform-specific, of course) nicely:

struct qinfo
{
    char name[50]; // string lives inside the struct
    int nr;
};
qinfo queues[] = {
    {"QALARM", 1}, // the literals are used to initialize the char array
    {"QTESTLONGNAME", 2}, // they should not be otherwise
    {"QTEST2", 3},        // compiled into the program
    {"QIEC", 4}
};


it looks ok for me. Cant see anything wrong.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜