具有整数的数组的数组
您将如何将二维整数数组存储为类变量?
如果你想要一个整数数组,你可以:
类声明
int * myInts;
实现
int ints[3] = {1,2,3};
myInts = ints;
但是如果你想存储一个由整数组成的数组怎么办?
像这样:
int ints[3][3] = {{1,2,3}, {1,2,3}, {1,2,3}};
我不想限制类声明中数组的大小,所以我想我必须使用指针,但是如何呢?
How would you go about storing a 2 dimensional array of ints as a class variable?
If you want an array of ints you go:
Class declaration
int * myInts;
Implementation
int ints[3] = {1,2,3};
myInts = ints;
But what if you want to store an array of arrays with ints?
Like this:
int ints[3][3] = {{1,2,3}, {1,2,3}, {1,2,3}};
I don't wanna limit the size of the arrays in the class declaration so I guess I have to go with pointers, but how?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为了将来参考,这是我的结论:
类声明
实现
这是我自己对评论中提供的链接的解释,我的 C 技能相当低,所以请考虑到这一点;)也许有更好的方法可以一次输入多个数字,比如 {123,456,789} 之类的,但这超出了我现在的要求!
For future reference, this is my conclusion:
Class declaration
Implementation
This is my own interpretation of links provided in comments and my C skills are pretty low so take that into consideration ;) Maybe there are better ways to put in multiple numbers at a time with {123,456,789} or something, but that is beyond my requirements for now!
我已经为你写了示例:
I've wrote sample for you:
如果要动态分配内存,换句话说,在运行时定义数组的大小,则需要将数组声明为指针,对其进行 malloc,然后在运行时向每个索引添加另一个 int 数组。您无法真正在类级别声明和动态分配。如果您使用 cocoa/iphone sdk,您可以使用 NSMutableArray。
您还可以创建自己的类来构造二维数组并公开推送和弹出 int 对象的方法,例如 [IntegerArray Push:x,y,n];
这是使用 的示例正如 Daniel R Hicks 指出的那样,双重引用。
If you want to dynamically allocate memory, in other words define the size of the arrays at runtime, then you need to declare the array as a pointer, malloc it, and then add another array of ints to each index at runtime. You can't really declare and dynamically allocate at the class level. If you are using cocoa/iphone sdk you can use NSMutableArray.
You could also create your own class that constructs a two dimensional array and exposes methods to push and pop int objects like [IntegerArray push:x,y,n];
Here's and example of using a double reference as Daniel R Hicks pointed out.