Tree - dynamic array

Hello I have a problem creating dynamic array in struct. This is a school project and I have done it using static array , but was wondering how to do it with dynamic array.

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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <string>
#include <iostream>
#include <conio.h>
using namespace std;

int countRes; // Counter for dynamic array
struct Tree{
	int address;
	string* StrArray = new string[countRes]; // Dynamic array
	//string Strarray[20]; // Static array
	int countStat = 0; // Counter for the array 
	Tree* L;
	Tree* R;
};
typedef Tree* Point;

void add_S_tree(int x, Point &p)
{
	if (p == NULL)
	{
		p = new Tree;
		p->address = x;
		cout << "Enter number of residents :";
		cin >> countRes;
		p->countStat = countRes ;
		string y;
		for (int i = 0; i < countRes; i++){
			cout << "Enter resident name :";
			cin >> y;
			p->StrArray[i] = y;
		}
		p->L = NULL;
		p->R = NULL;
	}
	else if (x<p->address)  add_S_tree(x, p->L);
	else if (x>p->address) add_S_tree(x, p->R);
}


int main()
{
	Point root;
	int x;
	root = NULL;
	cout << "Enter address: ";
	cin >> x;
	while (x != 0)
	{
		add_S_tree(x, root);
		cout << "Enter address: ";
		cin >> x;
	}

}
You either need a constructor, and pass countRes to that constructor, or you'll need to dynamically create the array yourself. Don't do it in the struct declaration.
You'll also need to free the memory once you're done with it.
Topic archived. No new replies allowed.