Let’s define this struct:
struct MyStruct {
int firstInt;
int secondInt;
char * firstString;
char * secondString;
};
I’m trying to initialize a struct like this:
MyStruct s = {4, 5, {'a', 'b', 'c'}, "abc"};
But it’s not working. Is there any way to do it? (the firstString is required not to have ‘\0’ at the end)
Since your requirement is to not have a null terminator at the end, you have to use an array for
firstString:Then you can initialize it like this:
You cannot initialize a
char*with{'a', 'b', 'c'}because you have to provide storage for the characters, achar*is only able to point at something."abc"happens to be a constant string literal which is stored in read only memory, so you are able to make thechar*point at that.Also, in C++,
"abc"is a constant which cannot me modified, so you should changechar * secondString;toconst char * secondString;.