Change private classes array size..?

Is there a way to change a private classes array size? I have a program where I want to add indexes to an array whenever a new object is created.

Here's my code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#define SIZE 1

class InstructionMemory {
private:
	string im [SIZE];
public:
	string fetch(int pc)
	{
		return im[pc];
	};

	void store(string a, int index)
	{
		int temp = SIZE - 1;
		if (temp < index)
		{
			string *im = new string [index]; // change the size?? Not working
		}
		im[index] = a;
	};

	friend class ControlUnit;
};
You can't change the size of an array declared like that. It needs to be dynamically allocated.
Three things wrong with line 17:

1. as Zhuge points out, im is an array, not a pointer.
2. if im were a pointer, you would be leaking memory.
3. the previous contents of im are not copied, resulting in losing all previously stored instructions.

Best to consider using vector<string> for im.
im is a pointer. It is a local variable inside the if scope. (but that is an error)
Also line 19 is out of bounds
Best to consider using vector<string> for im.


+100 @ This

No need to reinvent the wheel here. Just use a vector:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class InstructionMemory {
private:
	vector<string> im;
public:
	string fetch(int pc)
	{
		return im[pc];
	};

	void store(string a, int index)
	{
		if (index >= im.size())
			im.resize(index+1);
		im[index] = a;
	};

	friend class ControlUnit;
};
Last edited on
Thanks a lot for all of your replies!! Disch, thanks for the example.
Topic archived. No new replies allowed.