×

Discussion Board

Results 1 to 3 of 3
  1. #1
    Registered User
    Join Date
    Dec 2003
    Posts
    45

    Application error writing to class

    Hi,

    This is driving me mad. I've created a simple class:


    class MYCLASS
    {

    int x, y;
    int Alive;

    }

    And create some instances of it with:

    MYCLASS[] Bullets = new MYCLASS[10];

    This is all fine. But when I come to use it, I get an application error on runtime. For example the following code causes the problem.

    for( x = 0; x < 10; x++ )
    {
    Bullets[x].x = 0;
    Bullets[x].y = 0;
    Bullets[x].Alive = 0;
    }

    I really cant see why this causing an application error as I have one other more complex class working. I can also replace this particular class with a simple int array and it works fine, so there is something about the way I'm doing classes I guess. I'm not out of heap, as the new works as is. It's just reading or writing to the class instances that cause the problem.

    Any ideas?

    Thanks in advance.

  2. #2
    Super Contributor
    Join Date
    Mar 2003
    Location
    Israel
    Posts
    2,280
    You're creating the array (new) but not the objects it contains:
    Code:
    MYCLASS[] Bullets = new MYCLASS[10];
    for( x = 0; x < 10; x++ )
    {
    Bullets[x] = new MYCLASS();
    Bullets[x].x = 0;
    Bullets[x].y = 0;
    Bullets[x].Alive = 0;
    }
    When you "new" the array you only allocate space for the object references, not for the objects themselves. So you have to "new" each object to allocate the space for it's fields.

    shmoove

  3. #3
    Registered User
    Join Date
    Dec 2003
    Posts
    45
    ah yes! I'm a fool

    Thanks a lot. Sometimes you cant see for looking.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
×