Skip to main content
gamedev.net
🔒 Locked

Initializing Multi-Dimensional Arrays

Started by sysdomatic Jan 12, 2003 at 12:08 PM 0 replies 100+ views
Original Post
sysdomatic
sysdomatic
Hi all, I''m new here, and was wondering if someone might be able to help me with a couple of things. I just can''t get my head around it, not for lack of trying. Anyways, I basically have two questions: 1) How do I go about initializing a multi-dimensional array with a bunch of data if I don''t know before hand the number of rows or columns? For instance, I am trying to initialize a percents[][] array with a number of groups of percentages. For example: {0.2, 3.1, 4.8, 5.4}; {2.3, 2.8, 4.3}; Is it possible to do this dynamically, or do I have to declare the number of columns before hand, like percents[][1]? 2) If I have a multi-dimensional array that is seeded with values now, like let''s say percents[2][5], how would I use the sizeof function to return: number of rows (3), and number of columns per row? Basically I want to iterate through the percent rows, and then find the number of items for each column. So first I would need to find the total number of columns to set up my first loop, and then find the number of columns per row as I go through the loop. Any suggestions? Sorry for the long message, hoping someone can help me out. Thanks, Dave
civguy
civguy
1)

vectors replace arrays in C++

    
#include <vector>

int main() {
using std::vector;
vector<vector<double> > percents;
percents.push_back(vector<double>(4));
percents.push_back(vector<double>(3));

//values set as in your example

percents[0][0] = 0.2;
percents[0][1] = 3.1;
percents[0][2] = 4.8;
percents[0][3] = 5.4;
percents[1][0] = 2.3;
percents[1][1] = 2.8;
percents[1][2] = 4.3;
}

but if you want the bad old stuff:

        
int main() {
double** percents = new double*[2];
percents[0] = new double[4];
percents[1] = new double[3];

//values set as in your example

percents[0][0] = 0.2;
percents[0][1] = 3.1;
percents[0][2] = 4.8;
percents[0][3] = 5.4;
percents[1][0] = 2.3;
percents[1][1] = 2.8;
percents[1][2] = 4.3;

delete[] percents[0];
delete[] percents[1];
delete[] percents;
}



2)
sizeof(pointer) == 4 (on 32-bit systems. gotta be careful to mention every small detail here in gamedev or ppl will jump on me :D )
your multidimensional array is nothing but a pointer to an array of pointers.

But with vectors, you get what you want:
percents.size() == 2
percents[0].size() == 4
percents[1].size() == 3

[edited by - civguy on January 12, 2003 1:29:53 PM]

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.