Anyone can help to make a dynamic list in C++.?

In the study faced with the fact that the example in the textbook was not working.
Thanks in advance
#include <iostream>
using namespace std;
//The structure of two fields: an integer and
//a pointer to a variable of the structure:
struct DList{
int m;
DList *p;
};
//The function to access an element of a dynamic list:
void getm(int k,DList *q){
int i;
DList *t,*t1;
t=q;
for(i=1;i<k;i++){
t1=t->p;
t=t1;}
cout<<"Value is "<<t->m<<endl;}
int main(){
int i,n,k;
DList *q0,*q1,*q2;
//Create the initial list item:
q0=new DList;
q1=q0;
//Define the number of elements in the list:
cout<<"Enter n= ";
cin>>n;
//Create a dynamic list:
for(i=1;i<n;i++){
 cout<<"Value of m= ";
cin>>q1->m;
 q2=new DList;
q1->p=q2;
q1=q2;
}
cout<<"Value of m= ";
cin>>q1->m;
//The last element of the list refers to the initial element:
q1->p=q0;
//Output values of integer fields of the list items:
do{
 cout<<"Value for index k= ";
cin>>k;
 //To complete the program you must enter 0:
if(!k){
for(i=1;i<=n;i++){
q1=q2->p;
 delete q2;
q2=q1;
}
 return 0;
}
getm(k,q0);
}while(true);
}
April 3rd 20 at 18:36
1 answer
April 3rd 20 at 18:38
Solution
When n=1 is a list of 1 element, and q2 is not initialized. But when you delete still delete is called q2. The program either will not compile (if the compiler is smart enough), or falls into segfault.
That should work:
if(!k){
 q1 = q0;
for(i=1;i<=n;i++){
q2=q1->p;
 delete q1;
q1=q2;
}
}


But still good to check for zero and negative n; and that new returned a valid pointer.
Thank you) - earnest.Torp commented on April 3rd 20 at 18:41

Find more questions by tags C++Data structures