Search code examples
c++stringdynamic-memory-allocation

cin input user for dynamic allocation of array of strings


i'm new at this, learn c++, try to dynamic allocate a array of strings and input every string by the user. so at first, the user input the number of strings, and then put every string using cin>>

int main() {


    int numberOfTeams;
    char** Teams;

    cout << "Enter the number of teams " << endl;
    cin >> numberOfTeams;

    Teams = new char* [numberOfTeams] ;

    
    for (int i = 0; i < numberOfTeams; i++) {
        
            cin >> Teams[i];
                
    }

    delete[] Teams;

    return 0;
}

the program throw me out after cin one string. the error i get is :

 Exception thrown: write access violation.
**_Str** was 0xCEDECEDF.

i cant use "string" veriable, only array of chars.

thank you all


Solution

  • Something like this

    const int MAX_STRING_SIZE = 1024;
    
    int main() {
    
    
      int numberOfTeams;
      char** Teams;
    
      std::cout << "Enter the number of teams " << std::endl;
      std::cin >> numberOfTeams;
    
      Teams = new char*[numberOfTeams];
      for (int i = 0; i < numberOfTeams; i++) {
        Teams[i] = new char[MAX_STRING_SIZE];
        std::cin >> Teams[i];
      }
      for(int i = 0; i < numberOfTeams; ++i) {
        delete [] Teams[i];
      }
      delete [] Teams;
    
      return 0;
    }