Home > Blockchain >  cin input user for dynamic allocation of array of strings
cin input user for dynamic allocation of array of strings

Time:12-15

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

CodePudding user response:

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;
}

CodePudding user response:

A char** is a pointer to an array of character pointers. First thing you do is allocate the array of character pointers with Teams = new char*[numberOfTeams]; Teams now points to the first char* out of numberOfTeams char* pointers. Your mistake is that for each char* pointer in the array, you did not perform an allocation. Here is the correct solution.

#include <iostream>
using namespace std;
int main() {

    int numberOfTeams;
    int teamNameLength = 32;
    char **Teams;

    cout << "Enter the number of teams " << endl;
    cin >> numberOfTeams;
    Teams = new char*[numberOfTeams];

    for (int i = 0; i < numberOfTeams; i  )
    {
        Teams[i] = new char[teamNameLength];
    }

    for (int i = 0; i < numberOfTeams; i  ) {
        cout << "Enter team name " << i 1 << endl;
        cin >> Teams[i];
    }

    for (int i = 0; i < numberOfTeams; i  ) {
        delete[] Teams[i];
    }
    delete[] Teams;

    return 0;
}
  • Related