Resize canvas

Ok so First i have to create a Canvas using this fucntion
1
2
3
4
5
6
7
8
char ** allocate_canvas(int width, int height)
{
	char** arr = new char*[width];
	for (int i = 0; i < width; ++i) {
		arr[i] = new char[height];
	}
	return arr;
}


then i have to resize.... but i don't know how to do it so far this is what i have.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
void resize_canvas(char *** Cp, int old_width, int old_height, int new_width, int new_height, char wc)
{
	if (old_width < new_width) {
		Cp = new char**[new_width];
		for (int i = new_width - old_width; i < new_width; ++i) {
			*Cp[i][new_height] = wc;
		}
	}

	////////
	else if (old_width > new_width) {
		for (int i = old_width; i > new_width; --i) {
			delete Cp[i];
		}
	}

	////////
	if (old_height < new_height) {
		for (int i = 0; i < new_width; ++i) {
			Cp[new_width][i] = new char[new_height];
		}
		for (int i = new_height - old_height; i < new_height; ++i) {
			*Cp[new_width][i] = wc;
		}
	}

	/////////
	else if (old_height > new_height) {
		for (int i = old_height; i > new_width; --i) {
			Cp[i] = new char*[new_height];
		}
	}
	
}


this is where its called in the main function
1
2
3
resize_canvas(&C, 5, 6, 5, 10, 'e');
resize_canvas(&C, 5, 10, 3, 15, 'f');
resize_canvas(&C, 3, 15, 4, 7, 'g'); 
you have a few options.
1) you can create a new ** and allocate to the new size, copy the data over to it, and then destroy the old one.
2) you can use malloc, and realloc, to resize. This is ugly, and makes use of old C functions that cause issues on classes.
3) you can use a vector, which can grow on the fly.
4) you can use a 1d array, possibly with #2 or #3 ideas, and treat it like 2d. This saves a lot of trouble, you can for example transpose (flip the rows and cols) without resizing at all, and new/delete are cheaper, you can memcpy, and more.

if you don't need the current data, you can skip the copy steps.

forget old width. just delete the original, and allocate it again with the new values, if you don't want to keep the data. You are pretty close.

for( x = ... oldwidth ...)
delete[] cp[x];
delete[] cp;

then allocate it again like you did the first time around.


Last edited on
Topic archived. No new replies allowed.