• Advertisement


This topic is now archived and is closed to further replies.

pointer to a pointer

This topic is 5663 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I tried to do a search on this but the search engine on this board is down. I have a problem allocating a 2-dimensional character array which is read from a file. I set it up in my class as: char **map; and wish to fill this array, and getting the size of the array by reading the file.
ifstream file;	
int x=0;
int y=0;
char c;

	return false;
	file >> c;
	while(c != ''\n'')
		mapData[x][y] = c;

return true;

I realize that I probably have to allocate the size of the 2-dim array before reading in the data. I tried first reading the file and getting the mapWidth and mapDepth and then trying to allocate the array like this:
mapData = new char[mapDepth][mapWidth];
but that doesn''t work either. any help is appreciated.

Share this post

Link to post
Share on other sites
Cause I don't know how big the 2-dim array will be when I declare the variable.
Doh...I dunno why I didn't realize that the first time.

I have thought that to allocate a multidimensional dynamic array, you had to allocate each array separately with a for loop. I'm not sure if it's the easiest way, but it works.

char** data;

data = new (char*)[rows];
for (int m = 0; m < rows; m++)
data[m] = new char[cols];

Notice- the first new allocates an array of char*s, and the 2nd new allocates those into new 1d arrays of chars.

With 3d array, the first call is to char**, the 2nd to char*, and the 3rd to char, and so on for more dimensions. Here's the code for a 3d array if you're curious:

char*** array3d;

array3d = new (char**)[x];
for(int m = 0; m < x; m++)
array3d[m] = new(char*)[y];
for(n < 0; n < y; n++)
array3d[m][n] = new int[z];

And they say pointers aren't confusing...

EDIT - EEK tags!

[edited by - Neosmyle on September 15, 2002 5:58:11 PM]

[edited by - Neosmyle on September 15, 2002 5:59:15 PM]

Share this post

Link to post
Share on other sites
Just declare:

char* mapData;
mapData = new[mapDepth * mapWidth];

Then to find a certain position in the array:

char c = mapData[mapWidth * y + x];

You will either have to read through the data twice like you tried or better yet, store the depth and width in the file.

So your file would look like:

4 4

Then to load it use:

ifstream file;
int mapDepth, mapHeight;
file >> mapDepth >> mapHeight;
char* mapData = new[mapDepth * mapWidth];
in.eatwhite() //moves the stream to the start of the map data

Then load your data as before. To delete just use:

delete mapData;

Hope that helps.


Share this post

Link to post
Share on other sites

  • Advertisement