Цикл в массиве указателей

0

Я пишу код с массивом указателей и структур. Код:

struct Student_List{
    int roll;
    char name[20];
    int mark1;
    int mark2;
    int mark3;
    struct Student_List *next;
};
struct Student_List *Class[] = { NULL };// to generate student list for various classes.
struct Student_List *current =NULL;

struct Student_List * check(int rollNo, int classNo)
{

struct Student_List *temp=NULL;
temp=Class[classNo];

while (temp!=NULL) {
    if(temp->rollNo == rollNo)
    {
        //element is found
        return temp;
    }

    temp = temp->next;
}    
if(temp==NULL)
{
    //element not found
    return NULL;
}
//scan serially and if found return address of that node
//if no element found return NULL

}

//add elements to list pointed by Class
struct Student_List * add(char studentName, int rollNo,int classNo)
{
    struct Studen_List *newNode=(struct Student_List *)malloc(sizeof(struct Student_List ));
if (newNode == NULL) {
        printf("malloc failed\n");
        }  

newNode->roll=rollNo;
strcpy(newNode->name,studentName);
newNode->mark1=0;
newNode->mark2=0;
newNode->mark3=0;
struct Student_List *temp = NULL, *previous = NULL;

temp=Class[classNo];
prev = temp;
}

if(temp==NULL)
{
    Class[classNo]=newNode;
    return Class[classNo];


}

while(temp!=NULL)
{
    prev=temp;
    temp=temp->next;
}

prev->next=newNode;
return newNode;
//add node to end of the list
}

void Delete_List(struct Student_List *temp)
{
delete []temp;
//temp = NULL;

/*while(temp!=NULL)
{
    struct Student_List *del=temp;
    temp=temp->next;
    free(del);

}*/
}

int main();
{
int classNo,rollNo,i;
char *name;

printf("\nEnter Class No: ");
scanf("%d",&classNo);
printf("\nEnter Name: ")
gets(name);
printf("\nEnter Roll No: ");
scanf("%d",&rollNo);


current = check(rollNo,classNo);

if(current == NULL){
current = add(name,rollNo,classNo);
}
// others is the marks data fetched from file and calculations.
// this code is enough to reproduce my error.

for(int i=0;i<10;i++)
{
    Delete_List(Class[i]);
}
  return;
}

Проблема. Когда я присваиваю значения и выполняю вычисления, результаты были неправильными. При отладке я обнаружил, что начальный адрес моего Class[3] совпадает с Class[1]->nextRoll->nextRoll;

Я не могу удалить его. Пожалуйста, помогите мне удалить петлю. любая помощь с синтаксисом или предложениями приветствуется.

Теги:
arrays
pointers
struct

1 ответ

2

Вы не должны использовать malloc, используйте new:

struct Student_List{
    int roll;
    char name[20];
    int mark1;
    int mark2;
    int mark 3;
    Student_List *nextRoll;
};

Student_List * Class[] = { NULL };

int main();
{
    // various initializations

    // for each new student, do this
    Student_List *newNode=new Student_List;
    newNode->next = Class[0]; // 0 is the Class of the student
    Class[0] = newNode;

    // code to fetch data from text file and perform calculations.

    // do not delete Class; !!
}

Обратите внимание, что ваш подход неправильный, вы должны использовать STL как можно больше. Пример:

struct Student {
    int roll;
    std::string name;
    int mark1;
    int mark2;
    int mark3;
};

typedef std::list< Student > Class;

typedef std::map< std::string, Class > Classes;
Classes classes;

int main()
{
    Student s;
    s.name = "Daniel";
    // ...

    classes[ "1b" ].push_back( s ); // Add student to a class "1b".
}
  • 0
    Спасибо за помощь. и я знаю, что STL будет более полезным, но, к сожалению, я этого не знаю. хотя я начал изучать его, но из-за некоторых ограничений я должен завершить этот код, как было предложено предыдущим человеком, работающим над ним.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню