gpt4 book ai didi

c++ - 在结构中初始化字符串数组

转载 作者:行者123 更新时间:2023-11-28 00:55:44 25 4
gpt4 key购买 nike

#include<iostream>
#include<string>
using namespace std;
int main(void) {

struct STRCT {
int num;
string str1,
arrStr1[],
str2,
arrStr2[];
};

int a;
string b[2],
c[3],
d,
e;

a = 10;

b[0] = "hello";
b[1] = "world";

c[0] = "stack";
c[1] = "over";
c[2] = "flow";

d = "random";
e = "text";

//how do i intialize the arrays (arrStr1[] and arrStr2[]) in aStruct along with the rest of items?
//is it like this?

//i want aStruct[] to be an array and i want its size to be declared from the start to later be filled with vals

STRCT aStruct[2];

//then later in the program i want to assign aStruct[] vals

aStruct[0] = {a, //int
d, //string
{b}, //string[]
e, //string
{c}}; //string[]
}

所以基本上我想创建一个结构数组,其中包含数组,然后获取正确的值,然后将正确的值分配给结构数组内的数组。非常感谢您的帮助

最佳答案

结构中的数组声明完全是非法的。 C++ 不支持将无大小数组声明为类成员。即使某些 C++ 编译器支持 C99 风格的“struct hack”声明,也只允许一个无大小数组,并且该数组必须是结构的最后一个成员。

你想在你的结构中包含数组——你必须给它们特定的编译时大小。如果没有特定的编译时间大小,您将不得不使用指针或 std::vector

在您的示例中,b 的大小为 2c 的大小为 3。您可以声明具有相同大小的结构

struct STRCT {
int num;
string str1, arrStr1[2], str2, arrStr2[3];
};

然后初始化如下

STRCT aStruct[2] = 
{
{
a,
d,
{ b[0], b[1] },
e,
{ c[0], c[1], c[2] }
}

// The rest of the array is value-initialized
};

这就是普通数组所能达到的极限。如果您想要更灵活的东西,将数组直接嵌入到结构中对您没有帮助。手动构建必要的内存结构或使用 std::vector

关于c++ - 在结构中初始化字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11464792/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com