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}
};
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With