Stack Exchange
issue when ordering an array of structs in C
I want to order an array of structs by the first letter of a student´s name. The code that I made so far is the following:
#include <stdio.h>
#include <stdlib.h>

typedef struct{
    int cod;
    char* name;
    int mark;
}student;

void print(student* class){
     int i;
     for (i=0;i<4;i++){
         printf("%d\n",class[i].cod);
         printf("%s\n",class[i].name);
         printf("%d\n",class[i].mark);
         printf("\n");
     }
}

int main(int argc, char *argv[])
{
  int ind,i;
  int cod=1000;
  student class[4];
  student temp;
  int lengthData=10;
  for (i=0;i<4;i++)
  {
         class[i].name=malloc(sizeof(char)*lengthData);
  }
  class[0].cod=cod;
  class[0].name="Joseph";
  class[0].mark=15;
  cod++;
  class[1].cod=cod;
  class[1].name="Jonathan";
  class[1].mark=16;
  cod++;
  class[2].cod=cod;
  class[2].name="Karen";
  class[2].mark=17;
  cod++;
  class[3].cod=cod;
  class[3].name="Anna";
  class[3].mark=20;
  print(class);


  for (ind=1;ind<4;ind++){
      temp=class[ind];
      i=ind-1;
      while (i>=0){
            if (temp.name[0]<class[i].name[0]){
                class[i+1]=class[i];
                class[i]=temp;
                i--;
           }
           else break;
      }
  }
  printf("ordered data\n");
  print(class);
  system("PAUSE");

  return 0;
}

I am using DevC++ and when I run it the program hangs, but when I add the following lines before the loop for the bubble sort (only for testing):
class[3]=class[2];
printf("%s\n",class[3].name);

  for (ind=1;ind<4;ind++){
...

The program works even though one record (3) has been replaced by the data of record (2).
Any help?

You have quite a few problems:
First of all you leak memory, since you allocate memory and make name point to that, then you make name point somewhere else. You need to copyinto the memory you allocate.
Secondly, also with the name member, once you copy into the memory, you will go out of bounds since you only allocate five bytes for each string, but you have strings of up to at least nine characters (ten with the terminator).
Thirdly, and more about going out of bounds, your class array only have three elements, yet you access four elements of the array.
The reassignment of the name pointer won't cause more problems than a temporary memory leak, since you don't attempt to pass the pointer to free. The second problem isn't really an issue because you don't copy the strings yet. The third problem on the other hand, that will lead to undefined behavior as soon as you execute that code.

I have made the fixes 2 and 3, but stills the unexpected behaviour comes out, what is wrong? thanks

now it works, thank you, I would try to fix number 1
