Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

thank you all

>Solution :

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading