fatal error, while input array of char*

this is the code----------

int main()
{
int noOfChefs, noOfEmails;
cin >> noOfChefs >> noOfEmails;

char* chefWithCountry[ 100 ] = {"dsa", "sdf"};

int i = 0;
while( noOfChefs-- )
{

cin >> chefWithCountry[i];
i++;
}


}
But after the first input, it stops executing
The while statement is meant to execute on a true statement. When you decrement the noOfChefs variable the statement is true. Instead, trye

while(noNoChefs > 0)

then decrement the noNoChefs variable within the loop.
You have an array of pointers to char, but they are not properly initialised.
Notice the use of new [] and delete [].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>

    using namespace std;

int main()
{
    const int size = 100;
    const int width = 30;
    char * chefWithCountry[size];

    // allocate memory
    for (int i=0; i<size; i++)
        chefWithCountry[i] = new char[width];

    int noOfChefs;
    cin >> noOfChefs;
    cin.ignore(1000,'\n'); // remove newline from input buffer

    if (noOfChefs > size)
        noOfChefs = size;

    int i=0;
    while( i < noOfChefs )
    {
        cin.getline(chefWithCountry[i], width);
        i++;
    }

    // display contents of the array
    for (int i=0; i<noOfChefs; i++)
        cout << chefWithCountry[i] << endl;

    // release memory
    for (int i=0; i<size; i++)
        delete [] chefWithCountry[i];

    return 0;
} 
Last edited on
Topic archived. No new replies allowed.