1

I am trying to store values like "01" and "10" into an array but the int array would take "01" as "1". Hence I decided to use string array.While declaring the string array, I initialized it with

string array[n] = {0};

On compiling the code it shows an error saying :

"terminate called after throwing an instance of 'std::logic_error'
what():  basic_string::_M_constructnull not valid"

While just changing the type of the array to integer, it works fine.

I tried to not initialize the

string array[n]={0};

The code then works fine!

Can we conclude that the string type array cannot overwrite the values already stored in the elements?

#include<bits/stdc++.h>

using namespace std;
int main(){
    int n;
    cin>>n;
    string arr[n] = {0};
    for(int i=0; i<n; i++){
    cin>>arr[i];
    cout<<arr[i];

    }  
 }

this is the output of the code:

1
terminate called after throwing an instance of 'std::logic_error'
what():  basic_string::_M_constructnull not valid
NathanOliver
  • 150,499
  • 26
  • 240
  • 331
Sankalp
  • 13
  • 3
  • 2
    `string arr[n] = {0};` -- This is not legal C++. Arrays in C++ must have their size denoted by a compile time constant, not a runtime value. Assign just to a `string` (not an array) the value `0` and ask again. – PaulMcKenzie Feb 15 '19 at 14:12
  • No you can't conclude that. Newbies know very little about C++ (obviously) so don't try and reason about it too much, you're probably starting from false assumptions. – john Feb 15 '19 at 14:20
  • [Why should I not #include ?](https://stackoverflow.com/q/31816095/2311167) – Adrian W Feb 15 '19 at 14:30

1 Answers1

4

You have two problems with

string arr[n] = {0};

First, n is not a compile time constant so that makes arr a VLA (Variable Length Array). Those are not standard and are only supported as an extension by some compilers. You can use -pedantic compiler flag to stop if from compiling.

Secondly the = {0} part is going to initialize the first string in the array with the integer 0. Since 0 is also the null pointer value it gets treated as a pointer and the compiler tries to construct a string from a null pointer. This is undefined behavior and in this case std::string throws an exception.

To fix all of this use a std::vector (which can have a run time size) and let it default construct all of the elements for you. You can do that like

std::vector<std::string> arr(n);
NathanOliver
  • 150,499
  • 26
  • 240
  • 331