How can I sort an array of structures in c

I need to sort an array of structures, each of which has a string that is a name. I want to do a simple sort using bubble sort and strcmp, but my code doesn’t work, it displays the last name that I entered for the whole loop.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 16
#define N 5

struct Prova {
  char nome[SIZE];
};

void sort(struct Prova *ptr) {
  char temp[SIZE];

  for (int i = 0; i < N; i++) {
    for (int j = i + 1; j < N; j++) {
      if (strcmp((ptr + i)->nome, (ptr + j)->nome) < 0) {
        strcpy(temp, (ptr + i)->nome);
        strcpy((ptr + i)->nome, (ptr + j)->nome);
        strcpy(temp, (ptr + j)->nome);
      }
    }
  }
}

int main() {
  struct Prova * ptr;
  ptr = (struct Prova*) malloc(N * sizeof(struct Prova));

  for (int i = 0; i < N; i++) {
    scanf(" %s", (ptr + i)->nome);
  }

  sort(ptr);

  for (int i = 0; i < N; i++) {
    printf("%s\n", (ptr + i)->nome);
  }
}

Basically, you need to sort all the names in the structures and print them in ascending order using the first letter of the name.

UPDATED: Later I noticed this error in my code, thanks to everyone for the answers / suggestions. Now this:

  for(int i = 0; i < N - 1; i++)
{
  for(int j = i+1; j < N; j++)
  {
    // < 0 = Z-A  invece > 0 = A-Z
    if(strcmp((ptr+i)->nome,(ptr+j)->nome) > 0)
      {
        strcpy(temp, (ptr+i)->nome);
        strcpy((ptr+i)->nome,(ptr+j)->nome);
        strcpy((ptr+j)->nome, temp);
      }
  }

}
+4
source share
2 answers

OP is incorrectly encoded

    strcpy(temp, (ptr + i)->nome);
    strcpy((ptr + i)->nome, (ptr + j)->nome);
    // strcpy(temp, (ptr + j)->nome);
    strcpy((ptr + j)->nome, temp);

Many other improvements are possible.

  • Use qsort() @Karsten Koop
  • Confirm entry. Better to use fgets().
  • Simplify, check and free → struct Prova *ptr = malloc(sizeof *ptr * N); if (ptr == NULL) Handle_OutOfMemory(); ... // use ptr ... free(ptr);
0

- strcpy. :

for (int i = 0; i < N; i++) {
    for (int j = i + 1; j < N; j++) {
      if (strcmp((ptr + i)->nome, (ptr + j)->nome) < 0) {
        strcpy(temp, (ptr + i)->nome);
        strcpy((ptr + i)->nome, (ptr + j)->nome);
        strcpy((ptr + j)->nome, temp);
      }
    }
  }
}
0

Source: https://habr.com/ru/post/1696314/


All Articles