简体   繁体   English

如何在C ++中初始化双指针结构数组?

[英]How initialize double pointer struct array in C++?

I have a structure like below, 我的结构如下

struct myStruct
{
CString a;
int b;
CString c;
int d;
}

The char** array can be initialized as below, char **数组可以按以下方式初始化,

char **choices = (char *[]){ "New Game", "Continue Game", "Exit" };

Similarly how to initialize double pointer structure array. 同样如何初始化双指针结构数组。 My requirement is I should not do dynamic memory allocations using new or malloc. 我的要求是我不应该使用new或malloc进行动态内存分配。

I need below kind of initialization. 我需要下面的一种初始化。

myStruct** arr ={
....
....
....
....
};

First create a few myStruct objects: 首先创建一些myStruct对象:

myStruct ms1;
myStruct ms2;

Then create an array of pointers to myStruct : 然后创建一个指向myStruct的指针数组:

myStruct* pointerArray[] = {&ms1, &ms2};

Finally, you can take the pointer to first element of that array. 最后,您可以将指针指向该数组的第一个元素。 This is your "double pointer struct array" without dynamic allocation. 这是没有动态分配的“双指针结构数组”。

myStruct** arr = pointerArray;

 char **choices = (char *[]){ "New Game", "Continue Game", "Exit" }; 

This line has a few problems. 这条线有一些问题。

Firstly, the initialization syntax that you use is ill-formed in C++. 首先,您使用的初始化语法在C ++中格式错误。 Compound literals are a C99 feature and are not in the C++ language. 复合文字是C99的功能,不是C ++语言。

Secondly, you convert string literals to non-const char* . 其次,将字符串文字转换为非常char* String literals are const in C++, and such conversion from const to non-const is ill-formed (since C++11; prior to that the conversion was deprecated). 字符串文字在C ++中是const,并且这种从const到非const的转换格式不正确(自C ++ 11起;在不赞成使用此转换之前)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM