如何初始化结构的2d对象数组。 [英] How to initialize 2d object array of strucuture.

查看:74
本文介绍了如何初始化结构的2d对象数组。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

但是当我访问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 of Guitar then you have to modify

Quote:

guitarlists[i] = (Guitar *)malloc(sizeof(Guitar));

as well.
[/update]


Please note: since you apparently are using C++, why don't you use C++ 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆