0

Below are two structures viz Stu and Class. I have declared array of pointers of type Class in main and passing that to Delete function so that I can deallocate the memory(using free).

When I compile this code it shows same warning on many lines like in the Delete function below.

typedef struct Stu {
  struct Stu *prev, *next;
  unsigned int Roll_No, Marks, Id;
  char Name[20], Address[20];
} Stu;

typedef struct Class {
  Stu *next;
  char Class_Name[10];
  unsigned int Total_Stds;
} Class;

void Delete(Class *cls[], unsigned int cha) {
  unsigned int i;
  Class *temp;

  for (i = 0; i < cha; i++) {
    printf("%s removed\n", cls[i]->Class_Name);
    temp = cls[i];
    cls[i] = cls[i]->next; // Warning comes here
    free(temp);
  }
}


int main() {
 Class *cls[5];
 ...
 Delete(cls,c);
 ...
 return 0;
}
John Bollinger
  • 160,171
  • 8
  • 81
  • 157
  • 6
    What is unclear in the error? `cls[i]->next` is of type `Stu*` and you try to assign that to `cls[i]`, which is `Class*` – Yksisarvinen Mar 18 '22 at 12:09
  • you need to cast between the types – nullqube Mar 18 '22 at 12:10
  • 3
    @nullqube I don't what language OP uses, but at least in C++ (and I strongly suspect that in C as well) just casting error away will break literally everything on next access of `cls[i]`. – Yksisarvinen Mar 18 '22 at 12:13
  • 2
    I removed C++ tag as per our cross-tagging rules. There is nothing in the code indicating that this is C++. – Lundin Mar 18 '22 at 12:18
  • Amongst other errors, `main` is calling `Delete` with the wrong number of parameters. I guess the call should be `Delete(cls, n);` (for some `n` in the range 0 to 5). – Ian Abbott Mar 18 '22 at 12:23
  • If `Delete` is supposed to delete list of classes (specified by an array of class pointers) and delete the students in each class (specified by a linked list and possibly a list length), then you need an outer loop to delete the classes plus an inner loop to delete the students. – Ian Abbott Mar 18 '22 at 12:34
  • yes sir solved thanks a lot Stu *temp1,*temp2; for(i=0;iClass_Name); temp1 = temp2 = cls[i]->next; free(cls[i]); while(temp2) { temp2 = temp1->next; free(temp1); temp1 = temp2; } } – Tufail Gulzar Mar 18 '22 at 12:48

0 Answers0