0

I just want to know why it come the question that string subscript out of range,I have already initialized the string array.Thank you.

#include<bits/stdc++.h>
#define N 100000
using namespace std;
string s[N + 5] = {}, ss[N + 5] = { " " }, fs[N + 5] = { " " };
int main()
{
   int n, x; char c;
   cin >> n;
   for (int i = 0; i<n; ++i)
   {
      for (int j = 0; j<6; ++j)
       {
          scanf("%c", &c);//the error comes here.
          if (c == ' ') continue;
          s[i] += c;
       }
      ss[i] = s[i] + s[i];
      for (int j = 5; j >= 0; --j) fs[i][j] = s[i][5 - j];
   }
   int flag = 0;
   for (int i = 0; i<n; ++i)
   {
      for (int j = 0; j<n; ++j)
     {
        if (i == j) continue;
        if (find(s[i], fs[j]) || find(s[i], ss[j]))
        {
            flag = 1; break;
        }
      }
 }

}

田宇航
  • 3
  • 2

1 Answers1

2

1) Why should I not #include <bits/stdc++.h>?

2) Avoid global variables and use std::vector when size is unknown.

3) Why is using namespace std considered bad practice?

You're getting an out of range error because of fs[i][j] accessing empty strings f[i].

O'Neil
  • 3,790
  • 4
  • 16
  • 30
  • I'm sorry that I can't understand the reason, and the error seems to occur before the sentence – 田宇航 Jan 25 '18 at 06:39
  • @田宇航 `string fs[N + 5] = { " " }` declares `N+5` **empty** strings. Indexing them with `fs[i][j]` without filling them first is wrong as they're empty. – O'Neil Jan 25 '18 at 06:44
  • std::string s[N + 5] = {"123456"}, ss[N + 5] = { "123456" }, fs[N + 5] = { "123456" }; Can I modify the code like this? – 田宇航 Jan 25 '18 at 06:50
  • @田宇航 That would only initialize the first string. The `N+4` others would be empty. Don't forget my 2). – O'Neil Jan 25 '18 at 06:52
  • I add the module. for (int i = 0; i < N + 5; ++i) { s[i] = "123456"; ss[i] = 123456; fs[i] = "123456"; } and it seems work – 田宇航 Jan 25 '18 at 06:59
  • @田宇航 Or simply `std::vector fs(n, "123456");` ;) – O'Neil Jan 25 '18 at 07:02