Thread: Varying size classes

  1. #1
    Funniest man in this seat minesweeper's Avatar
    Join Date
    Mar 2002

    Varying size classes

    For a project I am involved in, I have a 2D array representing a map. I want to create a class representing a zone on the map. There will be numerous zones on my map that will be different sizes, i.e. varying numbers of map array elements in each zone. What I have in mind is as follows:

    class zone
    int num_of_squares;
    int square_coordinates[num_of_squares][2];
    //array giving map x and y coordinate for each square
    void set_squares(int a);
    void set_coordinates(int i, int pos_x, int pos_y);
    void zone::set_squares(int a)
    num_of_squares = a;
    void zone::set_coordinates(int i, int pos_x, int pos_y)
    square_coordinates[i][0] = pos_x;
    square_coordinates[i][1] = pos_y;
    //here I call zone1.set_squares and zone1.set_coordinates to initialise all class variables
    Is what I have in mind possible? I am getting errors and I think it is to do with the non-constant nature of num_of_squares.

    Any help would be much appreciated


  2. #2
    Use a VECTOR or a Linked List. This gives you an array of varying size throughout the program - When you create an array it can only be of a constant size.
    My Avatar says: "Stay in School"

    Rocco is the Boy!

  3. #3
    Banned master5001's Avatar
    Join Date
    Aug 2001
    Visalia, CA, USA
    It should work if number of_squares is set in the constructor, but I'm not a big fan of doing things this way. Not every compiler will compile this code correctly. You should just do dynamic allocation. You can do something like this in your set_squares function:

    void zone::set_squares(int a)
        //assumes square_coordinates is an **int
        num_of_squares = a;
        square_coordinates = new *int[a];
            square_coordinates[a] = new int[2];
    zone::~zone() {
        for(;num_of_squares--;) {
        delete[] square_coordinates;
    stupid smilies

  4. #4
    Funniest man in this seat minesweeper's Avatar
    Join Date
    Mar 2002
    Excellent!! Thank you. Thought I might need to dynamically allocate but wasn't sure how to implement it.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Generic heapsort
    By Sephiroth1109 in forum C Programming
    Replies: 15
    Last Post: 12-07-2007, 06:14 PM
  2. Exporting VC++ classes for use with VB
    By Helix in forum Windows Programming
    Replies: 2
    Last Post: 12-29-2003, 05:38 PM
  3. Prime Number Generator... Help !?!!
    By Halo in forum C++ Programming
    Replies: 9
    Last Post: 10-20-2003, 07:26 PM
  4. include question
    By Wanted420 in forum C++ Programming
    Replies: 8
    Last Post: 10-17-2003, 03:49 AM