cplusplus.com cplusplus.com
cplusplus.com   C++ : Forums : UNIX/Linux Programming : Segmentation fault outputting dynamic ar...
  Search:
- -
C++
Information
Documentation
Reference
Articles
Sourcecode
Forums
Forums
Beginners
Windows Programming
UNIX/Linux Programming
General C++ Programm...
Articles
Lounge
Jobs

-

question  Segmentation fault outputting dynamic array

softech (1)
#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
exception (321)
(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[]'.
|
jsmith (958)
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.
|

This topic is archived - New replies not allowed.
Home page | Privacy policy
© cplusplus.com, 2000-2009 - All rights reserved - v2.2
Spotted an error? contact us