0

让我们定义这个结构:

struct MyStruct {
    int firstInt;
    int secondInt;
    char * firstString;
    char * secondString;
};

我正在尝试初始化这样的结构:

MyStruct s = {4, 5, {'a', 'b', 'c'}, "abc"};

但它不起作用。有什么办法吗?(要求 firstString 结尾不能有 '\0')

4

4 回答 4

4

由于您的要求是最后没有空终止符,因此您必须使用数组firstString

struct MyStruct {
    int firstInt;
    int secondInt;
    char firstString[3];
    char * secondString;
};

然后你可以像这样初始化它:

MyStruct s = {4, 5, {'a', 'b', 'c'}, "abc"};

您不能用 with 初始化 a char*{'a', 'b', 'c'}因为您必须为字符提供存储空间, achar*只能指向某物。"abc"恰好是一个常量字符串文字,它存储在只读内存中,因此您可以char*指出这一点。

此外,在 C++ 中,"abc"是一个我无法修改的常量,因此您应该更改char * secondString;const char * secondString;.

于 2012-07-08T23:34:24.173 回答
2

您可以为此使用复合文字:

struct MyStruct {
    int firstInt;
    int secondInt;
    char * firstString;
    char * secondString;
};

struct MyStruct s = { 4, 5, (char[]){'a', 'b', 'c'}, "abc" };

这个结构是在 C99 中引入的;见N1256 草案第 6.5.2.5 节。一些编译器(尤其是微软的)可能不支持它。

请注意,在 C 中,类型struct MyStruct不能仅称为MyStruct; 这是 C 和 C++ 之间的区别。确保您正在编译您认为的语言。

需要注意的一件事是与复合文字关联的对象的生命周期。字符串字面量表示具有静态生命周期的数组对象,即该对象存在于程序的整个执行过程中。关联的数组对象(char[]){'a', 'b', 'c'}如果出现在函数体之外,则具有静态存储持续时间,但如果它出现在函数主体内部,则具有自动存储持续时间(与最里面的封闭块相关联)。如果您尝试s在定义它的块之外传递副本,这可能是一个问题。

于 2012-07-08T23:53:05.673 回答
0

一个微妙的点出现了。您的结构有两个char *,但没有存储来备份这些指针。你可能想要这样的东西:

struct MyStruct {
    int firstInt;
    int secondInt;
    char firstString[3];
    char secondString[4];
};
于 2012-07-08T23:30:12.767 回答
-1
#include <iostream>

using namespace std;

struct MyStruct {
    int firstInt;
    int secondInt;
    char * firstString;
    char * secondString;
};

int main()
{
    char arr[] = {'a', 'b', 'c','\0'};
    MyStruct s = {4, 5, arr, "abc"};

    cout << s.firstString << endl;

    return 0;
}

MyStruct s = {4, 5, {'a', 'b', 'c'}, "abc"};

{'a', 'b', 'c'} have no memory to store.It's a r-value. 

- 我认为。^-^

于 2012-07-08T23:57:02.247 回答