D
D
ddeel2019-12-18 22:18:44
C++ / C#
ddeel, 2019-12-18 22:18:44

Who can help compose dynamic list c++.?

When studying, I came across the fact that the example in the textbook was not working.
Thanks in advance

#include <iostream>
using namespace std;
//У структуры два поля: целое число и
//указатель на переменную структуры:
struct DList{
int m;
DList *p;
};
//Функция получения доступа к элементу динамического списка:
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;
//Создание начального элемента списка:
q0=new DList;
q1=q0;
//Определение количества элементов списка:
cout<<"Enter n= ";
cin>>n;
//Создание динамического списка:
for(i=1;i<n;i++){
   cout<<"Value m= ";
   cin>>q1->m;
   q2=new DList;
   q1->p=q2;
   q1=q2;
}
cout<<"Value m= ";
cin>>q1->m;
//Последний элемент списка ссылается на начальный элемент:
q1->p=q0;
//Вывод значений целочисленных полей элементов списка:
do{
   cout<<"Value for index k= ";
   cin>>k;
   //Для завершения программы нужно ввести 0:
   if(!k){
      for(i=1;i<=n;i++){
         q1=q2->p;
         delete q2;
         q2=q1;
         }
   return 0;
   }
   getm(k,q0);
}while(true);
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Ocelot, 2019-12-18
@ddeel

With n=1, a 1-element list is created and q2 is not initialized. But when deleting, delete q2 is still called. The program will either not compile (if the compiler is smart enough) or fall into a segfault.
This is how it should work:

if(!k){
      q1 = q0;
      for(i=1;i<=n;i++){
         q2=q1->p;
         delete q1;
         q1=q2;
         }
}

It's also a good idea to check for zero and negative n; and also that new returned a valid pointer.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question