让我们定义这个结构:
struct MyStruct {
int firstInt;
int secondInt;
char * firstString;
char * secondString;
};
我正在尝试像这样初始化一个结构:
MyStruct s = {4, 5, {'a', 'b', 'c'}, "abc"};
但它不起作用。有什么办法吗? (要求firstString末尾不能有'\0')
最佳答案
由于您的要求是末尾没有空终止符,因此您必须为 firstString
使用数组:
struct MyStruct {
int firstInt;
int secondInt;
char firstString[3];
char * secondString;
};
然后你可以像这样初始化它:
MyStruct s = {4, 5, {'a', 'b', 'c'}, "abc"};
你不能用 {'a', 'b', 'c'}
初始化一个 char*
因为你必须为字符提供存储,一个 char*
只能指向某物。 "abc"
恰好是存储在只读内存中的常量字符串文字,因此您可以使 char*
指向它。
此外,在 C++ 中,"abc"
是我无法修改的常量,因此您应该将 char * secondString;
更改为 const char * secondString;
。
关于c - 如何初始化一个(复杂的?)结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11387536/