dynamic array of strings problem

Can anyone figure out why each of these are writing to the same address space. I can't use anything else but a dynamic array of strings. When I write B's to generationB it also writes B's to generationA as you can see if you run it.

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
57
58
#include<iostream>
using namespace std;
            
            
            
int main()
{
    
    int numRows=5;
    int numColumns=5;
    string* generationA;
    string* generationB;
    
    generationA = new string[numRows];
    cout << "Generation A" << endl;
    for (int i = 0; i < numRows; i++)
    {
        for (int j = 0; j < numColumns; j++)
        {
            generationA[i][j]='A';
            cout << generationA[i][j];
        }
        
        cout << endl;
    }            
    
    generationB = new string[numRows]; 
    cout << "Generation B" << endl;
    for (int i = 0; i < numRows; i++)
    {
        for (int j = 0; j < numColumns; j++)
        {
            generationB[i][j] = 'B';
            cout << generationB[i][j];
        }
        
        cout << endl;
    }        
    cout << "Generation A again:" << endl;
    for (int i = 0; i < numRows; i++)
    {
        for (int j = 0; j < numColumns; j++)
        {
            cout << generationA[i][j];
        }
        
        cout << endl;
    }        
    cout << "Generation A is pointing at " << generationA <<endl
         
         << "Generation B is pointing at " << generationB <<endl;
             
    delete []generationA;    
    delete []generationB;
    
    system("pause");
}
        
Last edited on
You are not using strings correctly.

 
generationA = new string[numRows];


creates an array of strings, each of which is length 0.

Then your for() loop does this:

 
generationA[i][j] = 'A';


This accesses the jth element of each string. But each string is length 0, so the jth element does not technically exist.
Topic archived. No new replies allowed.