如何初始化结构的2d对象数组。 [英] How to initialize 2d object array of strucuture.
问题描述
但是当我访问Structure的属性时我得到了异常,我使用的代码在下面
我尝试了什么:
i有结构名称吉他,代码用于创建2D对象吉他对象
吉他**吉他手=(吉他**)malloc( sizeof (吉他*));
for ( int i = 0 ; i< row; i ++)
{
guitarlists [i] =(Guitar *)malloc( sizeof (吉他));
}
引用:吉他** guitarlists =(吉他**)malloc(sizeof(吉他*));
应该是
吉他**吉他手=(吉他**)malloc(行 * sizeof (吉他*));
[update]
As Thaddeus Jones 正确指出out,如果你需要一个吉他
的二维数组,那么你必须修改
引用:guitarlists [i] =(吉他*)malloc(sizeof(吉他));
以及。
[/ update]
请注意:因为你显然使用C ++
,为什么不使用C ++
编程语言和标准库功能(例如容器)?
如果你想要 r <的二维数组/ var> rows和 c 列,你可以这样做:
吉他** guitarlists =(吉他* *)malloc(r * sizeof(吉他*));
for(int i = 0; i< r; i ++)
{
guitarlists [i] =(Guitar *)malloc(c * sizeof(Guitar));
}
在C ++中,使用newnew和delete运算符是标准的:
< pre lang =c ++>吉他* guitarlists = 新吉他[row]; // 普通数组
delete guitarlists;或者我错过了一些位?
but when i access the attributes of Structure i get the exception, the code i used is below
What I have tried:
i have structure name "Guitar", code that is used to create 2 D array of Guitar Objects
Guitar ** guitarlists = (Guitar **)malloc(sizeof(Guitar *));
for (int i = 0; i < row; i++)
{
guitarlists[i] = (Guitar *)malloc(sizeof(Guitar));
}
Quote:Guitar ** guitarlists = (Guitar **)malloc(sizeof(Guitar *));
That should be
Guitar ** guitarlists = (Guitar **)malloc(row * sizeof(Guitar *));
[update]
As Thaddeus Jones correctly pointed out, if you need a bidimensional array ofGuitar
then you have to modify
Quote:guitarlists[i] = (Guitar *)malloc(sizeof(Guitar));
as well.
[/update]
Please note: since you apparently are usingC++
, why don't you useC++
programming language and standard library features (e.g. containers)?
If you want a 2D array of r rows and c columns, you can do this:
Guitar ** guitarlists = (Guitar **)malloc(r* sizeof(Guitar *)); for (int i = 0; i < r; i++) { guitarlists[i] = (Guitar *)malloc(c * sizeof(Guitar)); }
In C++ it is standard to use the "new" new and delete operators like that:
Guitar *guitarlists = new Guitar[row];//normal array delete guitarlists;Or am I missing some bits?
这篇关于如何初始化结构的2d对象数组。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!