Dynamic Array

Hi everyone.
I've been trying to write a code that do the following
The user write a number of words
The program store every word in memory
Here's the code i wrote :
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
55
56
 bool more=true;
    int d;
    char ch1[40],ch2[40],ch3[1];
    cout<<"Enter a word in capitals : \n";
    cin>>ch1;
    Darray T(ch1);
    while(more==true)
        {
            cout<<"More words ? (y/n)"<<"\n";
            cin>>ch3;
            if(ch3[0]=='y')
             {
                 cout<<"Enter a word in capitals : \n";
                 scanf("%s",&ch2);
                 T.Add(ch2);
                 cout<<"*********************************************************** \n";
                  T.print();

             }

class Darray
{
private:
    char word[20];
    char** T;
    int c;
public:
    Darray(char ch[20])      //Constructor of the class.
    {
        this->c=1;
        this->T=new char*[1];
        T[0]=ch;
    }
    void Add(char ch[20])  //Function to add elements to the array
    {
        char** P;
        P=new char*[c+1];
        for(int i=0;i<c;i++)
            {
                P[i]=T[i];
            }
        P[c]=ch;
        free(T);
        T=P;
        c++;
    }
    void print()      //Print the element of the array to the screen
    {
        for(int i=0;i<c;i++)
            {
                cout<<T[i]<<"\n";
            }
    }

};


The problem is when i run it: it goes
Word1
Word2
The first time and :
Word1
Word3
Word3
The second time.
It's like if the second word was replaced by the third.
Thanks everybody.
The line 15 calls the Add() with same address (ch2) every time. Every pointer in T.T (except the first) thus points to the same C-string (ch2).

Line 14 overwrites the content of ch2 on every iteration.

Why don't you use std::string and std::vector<std::string>? Why do you use scanf(), when you also use std::cin?


Edit: Trivia question. What is utterly wrong in line 43, when lines 31 and 37 use new?
Last edited on
Topic archived. No new replies allowed.