[英]How do I initialize this variable-size struct?
如何初始化下面声明的可变大小C ++结构“ StructB”:
#include <iostream>
#include <string>
typedef struct {
char* a;
int b;
} StructA;
typedef struct {
StructA* pointers[];
int pcount;
int numbers[];
int ncount;
} StructB;
int main()
{
StructB *sb = new StructB; // I need 'sb' to be allocated in the heap
sb->pcount = 5;
sb->ncount = 3;
sb->pointers = new StructA*[sb->pcount];
sb->numbers = int[sb->ncount];
}
我遇到了这些编译器错误。 这些错误是什么意思,我该如何解决? 谢谢。
In function 'int main()':
21:43: error: incompatible types in assignment of 'StructA**' to 'StructA* [0]'
22:19: error: expected primary-expression before 'int'
22:19: error: expected ';' before 'int'
听这不是C ++的好方法,您在C ++环境中进行C语言,如果它可以给您带来一些好处(IO,类型检查等)或用于学习,则可以。 C风格的动态内存分配完全是手动的。 释放也是如此。 由于您使用的是typedef,因此typedef可以使您和编译器的工作变得更加清晰。 这是一个折磨的例子,我想您可以做得到。 请注意,它是通过“艰难之路”完成的,这实际上是使用C ++进行C样式编码时的简便方法。
#include <iostream>
#include <string>
typedef struct {
char* a;
int b;
} StructA;
typedef StructA* A_p; // A_p is "pointer to structA" (contains address of struct)
typedef A_p* A_p_Array; // A_p_Array is "pointer to A_p" (aka StructA**) contains address of A_p
typedef int* int_Array; // int_Array is "pointer to int" contains address of integer
typedef struct {
A_p_Array A_pointers;
int pcount;
int_Array numbers;
int ncount;
} StructB;
int main()
{
int i;
StructA *sa = new StructA;
StructB *sb = new StructB;
sb->pcount = 5;
sb->ncount = 3;
A_p_Array tmp_A_array;
A_p tmp;
for ( i = 0 ; i < sb->pcount; i++)
{
tmp_A_array = new A_p; // create a StructA pointer
tmp = new StructA; // create a StructA
tmp_A_array = &tmp; // put address of tmp in mp_A_array
tmp_A_array++; // increment array address
}
sb->A_pointers = tmp_A_array; // A_pointers now contains address of dynamically created array
tmp_A_array = NULL; // clear pointer but do NOT delete!
int_Array tmp_i_array;
for ( i = 0 ; i < sb->ncount; i++)
{
tmp_i_array = new int(0); // c++ can create ints with initial values
tmp_i_array++;
}
sb->numbers = tmp_i_array;
tmp_i_array = NULL; // clear pointer but do NOT delete!
/****** USE Structs A & B *****/
// clean up the heap
A_p Ap;
for ( i = 0 ; i < sb->pcount; i++)
{
Ap = sb->A_pointers[i];
delete Ap; // each struct released separately
}
int* ip;
for ( i = 0 ; i < sb->ncount; i++)
{
ip = & sb->numbers[i];
delete ip; //each int released separately
}
delete sb;
return 0;
} // main
有更好的方法可以完成上述操作,这是发明c ++和高级语言的原因之一。 当您上课时,它会稍微容易一些,但您可以在其中遇到相同类型的问题,因此,现在放下指针和指针到指针将在以后为您服务。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.