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's 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;
相同
我無法刪除它。請幫我刪除循環。 歡迎提供任何有關語法或建議的幫助。
該代碼不能編譯,甚至沒有你需要幫助刪除的「循環」。你希望我們幫助你一個與你的問題無關的代碼?這裏有一個:'int main(){}',這個可以工作。 – DanielKO
向我們展示如何初始化和使用'Class'會很有用。 – Thanushan
這是C++還是C?只挑一個。 – user694733