开发者

Dynamic array of an object

Maybe the solution is very simple. It must be, but maybe I am overlooking something

I have:

public class Object {
    public int pos_x;
    public int pos_y;
}

Object testObject[] = new object[10]

and then somewhere in a function

testObject[1].pos_x = 1;

It force closes my app.. how? and why? What can be the cause of this.

Furthermore. Ideally I would need something like this

testObject[].add_new_object();
testobject[].remove_item(3);

can this be done?

Thank you fo开发者_高级运维r helping


You have allocated an array that can hold 10 objects.

You also need to allocate the objects.


I'm not sure about the language you are using - if C# you cannot use 'Object' as the class name.

First creating a custom object (the 'object' data type):

public class MyObject {
    public int pos_x;
    public int pos_y;
}

...fair enough, a very basic class that holds coordinates. Next you want to create an array of MyObject. To do that, you declare your array type as MyObject[] and provide an optional size:

MyObject[] myObjArray = new MyObject[10]; // this gives a zero-based array of 10 elements, from 0-9

Now, you have the task of filling the array. The most common method would be to use a counter variable that counts from 0 to 9, the same elements we have in our array:

for (int i=0; i<=9; i++)
{
    myObjArray[i] = new MyObject();

    // you can also assign the variables' values here
    myObjArray[i].pos_x = GetNextXVal(); // get the X value from somewhere
    myObjArray[i].pos_y = GetNextYVal(); // get the y value from somewhere
}  

Depending on your language, I'm sure we can point you to some good tutorials, books, or other references to help you get started.

Happy coding!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜