Из вашего кода (цикл do-while):
/* Add #include <assert.h> at top of file */
// Run #1
assert( pointer != NULL ) ;
beforepointer = pointer ; // beforepointer == pointer == start
assert( beforepointer != NULL ) ;
assert( beforepointer->name != NULL ) ;
cout << beforepointer->name << endl ; // Will print 'Start'
pointer = pointer->next ; // pointer->next == start->next == NULL
assert( pointer != NULL ) ; // SHOULD FAIL HERE (will abort)
// (pointer is now NULL)
// Run #2
beforepointer = pointer ; // beforepointer == pointer == NULL
assert( beforepointer != NULL ) ; // This would fail too
cout << beforepointer(== NULL)->name << endl ; // *** Segmentation violation!
...
Вы больше не указываете на что-либо действительное во 2-м цикле, перед указателем NULL.
Лучший способ распечатать список:
beforepointer = pointer ;
assert( beforepointer != NULL ) ;
while ( beforepointer != NULL ) {
assert( beforepointer->name != NULL ) ;
cout << beforepointer->name << endl ;
beforepointer = beforepointer->next;
}
EDIT:
Перефразируя ваш пример кода и используя стандартную библиотеку c ++, вы можете упростить все это следующим образом (используя векторы):
/**
* Wrapper function to prompt user for input
*/
istream & queryUser( const string & prompt, string & answer ) {
cout << prompt << ' ' << flush ;
getline( cin, answer ) ;
return cin;
}
/** Always useful emptiness test function */
bool isBlankOrEmpty( const string & s ) {
return s.empty() || s.find_first_not_of( " \t") == string::npos ;
}
/**
* The big main
*/
int main() {
vector<string> stations ; // list of station names
// ... Accept user input as long as input is entered
string newStationName ;
while( queryUser( "Enter new station name (or hit ENTER to exit)", newStationName ) ) {
// ... Quit if the line is empty
if ( isBlankOrEmpty( newStationName ) ) {
break ;
}
// ... Locate insertion point
vector<string>::iterator insertionPoint = stations.end() ; // append by default
// ... Have user specify where to insert the new station (if there is such an option)
if ( stations.size() > 1 ) {
// ... Where to insert?
string fromStation ;
if ( queryUser("Enter station it is from (top to bottom)", fromStation) && ! isBlankOrEmpty( fromStation ) ) {
vector<string>::iterator it = std::find( stations.begin(), stations.end(), fromStation ) ;
if ( it != stations.end() ) {
insertionPoint = ++it ; // move to position after the fromStation
}
}
}
// ... Insert the new station name
stations.insert( insertionPoint, newStationName ) ;
cout << "Your station list:" << endl ;
for ( auto & stationName : stations ) {
cout << stationName << endl ;
}
}
return 0 ;
}