in my function I am given a string array where it needs to be sorted via a specific ruleset which is also given - the main function works and the rule comparison ones work as well but the bubble sort keeps returning the input as output and I can't figure out why.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
void swap(char** s1, char** s2)
{
char** temp = s1;
s1 = s2;
s2 = temp;
}
main()
{
int i, j;
char** arr_of_strings = malloc(3 * sizeof(char*));//I allocated the array
arr_of_strings[0] ="wonder_woman";//with malloc and loops originally.
arr_of_strings[1] ="batman";
arr_of_strings[2] ="superman";
for (i = 0; i <2; i++)//the bubble array process:
{
for (j = 0; j < 3 - i - 1; j++)
{
if (strcmp(arr_of_strings[i], arr_of_strings[j]) > 0)
{
swap(&arr_of_strings[j], &arr_of_strings[j + 1]);
}
}
}
printf("The sorted strings are:\n"); //printing the function
for (int k = 0; k < 3; k++) {
printf("%s\n", arr_of_strings[k]);
}
}
output example:
The sorted strings are:
wonder_woman
batman
superman
I think you have a problem with your swap function' or the way you call it. anyway, this implementation works:
#include <stdio.h>
#include <malloc.h>
#include <string.h>
#define SIZE 3
int main()
{
int i, j; int n=SIZE; //n is a user input in the original program.
char temporary_string[32];
char* arr_of_strings[SIZE];
char* temp = NULL;
//input data
for (int l = 0; l < 3; l++)
{
scanf("%s", temporary_string);
arr_of_strings[l] = malloc(((strlen(temporary_string) + 1) *sizeof(char)));
strcpy(arr_of_strings[l], temporary_string);
temporary_string[0] = '\0';
}
//the actual sort
for (i = 0; i < n - 1; i++)
{
for (j = 0; j < SIZE - i - 1; j++)
{
if (strcmp(arr_of_strings[j], arr_of_strings[j + 1]) > 0) //simplification
{
//swap
temp = arr_of_strings[j];
arr_of_strings[j] = arr_of_strings[j + 1];
arr_of_strings[j + 1] = temp;
}
}
}
printf("The sorted strings are:\n");
for (int i = 0; i < n; i++) {
printf("%s\n" , arr_of_strings[i]);
}
// free allocated memory
for (int i = 0; i < n; i++) {
free(arr_of_strings[i]);
}
}
I hope it helps, if you have quastions I would be happy to answer =)