Segmentation fault outputting dynamic array

#include<iostream>
#include<string>

using namespace std;

int main()
{
int idNum, amt, count=0, count2=0, num=0;
string name, degrPrg, *cName;

cout<<"Enter Name: ";
getline(cin, name);
cout<<"Enter I.D Number: ";
cin >> idNum;
cout<<"Enter Degree Program: ";
cin.get();
getline(cin, degrPrg);

cout<<"How many courses are you doing this semester? ";
cin>> amt;

cName = new string[amt];
cin.get();

while(count < amt)
{
cout <<endl<<"Enter Course " << ++count << " Name: ";
getline(cin, cName[count]);
}

cout<< endl;

cout<<"Name: "<<name <<endl;
cout<<"I.D Number: "<<idNum <<endl;
cout<<"Degree Program: "<<degrPrg <<endl;


do
{

cout<<"Course " << ++count2 <<" Name: " << cName[count2] << endl;
}while(count2 < amt);

delete [] cName;

return 0;
}



//why am i getting a segmentation fault at the end of my program when it runs?
//what do i need to change or add?
Last edited on
(a) Please use code tags
(b) First state the question, then, if necessary, post some code
(c) 'new' and delete[] don't mix. Either use 'new' and 'delete' or 'new[]' and 'delete[]'.
You are walking past the end of your cName array inside your first while loop.
Note the first element you access in the array is at index 1 (because of the ++count on the line immediately before) instead of 0, which means you are accessing one beyond the end of the array for the last element.
Topic archived. No new replies allowed.