J'ai écrit le code suivant pour obtenir des chaînes triées dans un tableau de caractères 2-Dde caractères à bulles sorte
#include <stdio.h>
#include <string.h>
void swap(char *,char *);
void main() {
char a[20][20];
int Pass = 0, i = 0, j = 0, n;
printf("\nHow many elements you want to sort ? >> ");
scanf("%d", &n);
printf("\n\nEnter the elements to be sorted :\n");
for (i = 0; i < n; i++)
scanf("%s", a[i]);
for (Pass = 1; Pass < n; Pass++) {
for (j = 0; j < n - Pass; j++)
if (strcmp(a[j], a[j + 1]) < 0)
swap(a[j], a[j + 1]);
printf("\n\nPass = %d\n", Pass);
for (i = 0; i < n; i++)
printf(" %s ", a[i]);
}
}
void swap(char *a, char *b) {
char *t;
*t = *a;
*a = *b;
*b = *t;
}
Mais, je reçois la sortie comme
How many elements you want to sort ? >> 5
Enter the elements to be sorted :
1 2 3 4 5
Pass = 1
2 3 4 5 1
Pass = 2
3 4 5 2 1
Pass = 3
4 5 3 2 1
Pass = 4
Segmentation fault (core dumped)
Pourquoi est-ce que je rencontre la segmentation faute? (Le même code fonctionne correctement si j'utilise un tableau d'entiers au lieu d'un groupe de caractères)
principale doit retourner 'int ' –
Votre fonction' swap' est incorrecte. 1) 'char * t; * t = * a; ': Utilisation d'une variable non initialisée. 2) Ce qui devrait être échangé est un tableau plutôt qu'un pointeur (ou un 'char'). – BLUEPIXY
Gagnez du temps, activez tous les avertissements du compilateur: 'char * t; * t = * a; 'devrait avertir que' t' est utilisé avant l'initialisation. – chux