-1

I have got this code:

int n,m; // n - rows count , m - columns in each row count
cin >> n >> m;
string wiersze[n];
int wynik=0;
for(int i = 0; i < n;i++)
{
    cin >> wiersze[i];
}
for(int i = 0; i < n;i++)
{
    for(int j =0; j<m-1;j++)
    {
        cout << j << " " << j+1<<endl; // debbuging line 
        cout<<wiersze[i].at(j)<<wiersze[i].at(j+1)<<endl;   // debbuging line       
        if(wiersze[i].at(j) == wiersze[i].at(j+1))wynik++;
    }
}

When there are two the letters in the string, I should increase variable wynik. I do not know why, but running that code on this example:

4 4

aaba

aaab

aaba

bbaa

causes std::out_of_range error on string::at in row if(wiersze[i].at(j) == wiersze[i].at(j+1))wynik++;.

I tried debbuging and added two lines in loop to see what is happeing. Results:

0 1

aa

1 2 ab

2 3

ba

0 1

aa

1 2

aa

2 3

ab

0 1

aa

1 2

ab

2 3

ba

0 1

bb

1 2

ba

2 3

aa

Please look at two last lines - it shows exactly that what by computation next line does not exists! I, of course, tried to look for "stupid" mistakes and small debugging, but without any result exepct that, you can see above. Please help me in my case.

TN888
  • 7,659
  • 9
  • 48
  • 84

1 Answers1

0

First of all you CAN NOT allocate memory for array as you did. In wiersze[n] variable n must be known at compile time, but here it is not. You have to initialize the array dynamically:

string* wiersze = new string[n];
NiRR
  • 4,782
  • 5
  • 32
  • 60
Dakorn
  • 883
  • 6
  • 11
  • Ok, but I never had problem when I initialized array like that. – TN888 Jun 09 '14 at 17:15
  • 4
    Could you please kindly not answer C++ questions unless you know how to C++? Protip: `new[]` is the worst language feature in C++. – Puppy Jun 09 '14 at 17:21