I was doing a school project of making a program which uses insertion sort to sort the name of cities. While doing this, This error appeared and I can't find an appropriate answer or a solution to this problem.
#include <stdio.h>
#include <string.h>
#define MAX_COUNT 10
void ISAscend(const char* astr_list[], int amax_count) {
int i, j;
const char* temp;
for (i = 0; i < amax_count - 1; i++) {
j = i;
while (strcmp(astr_list[j], astr_list[j + 1]) > 0) {
temp = astr_list[j];
astr_list[j] = astr_list[j + 1];
astr_list[j + 1] = temp;
j--;
}
}
}
void ISDescend(const char* astr_list[], int amax_count) {
int i, j;
const char* temp;
for (i = 0; i < amax_count - 1; i++) {
j = i;
while (strcmp(astr_list[j], astr_list[j + 1]) < 0) {
temp = astr_list[j];
astr_list[j] = astr_list[j + 1];
astr_list[j + 1] = temp;
j--;
}
}
}
int main()
{
int i;
const char* str_list[MAX_COUNT] = {
"seoul", "tokyo", "delhi", "shanghai", "cairo",
"mumbai", "beijing", "dhaka", "osaka", "karachi"
};
printf("Insertion Sort (global big cities)");
printf("\n-------------------------------------------\n");
printf("[Ascending order] : ");
ISAscend(str_list, MAX_COUNT);
for (i = 0; i < MAX_COUNT; i++)
printf("%s - ", str_list[i]);
printf("\n[Descending order] : ");
ISDescend(str_list, MAX_COUNT);
for (i = 0; i < MAX_COUNT; i++)
printf("%s - ", str_list[i]);
printf("\n-------------------------------------------\n");
return 0;
}
I'm still learning programing, and I'm so confused. Can anyone give me a not-too-complicated answer for this problem? This project was by a discrete math professor and he demanded us to search for any necessary information because he didn't teach any of this, and I just learned what pointer is last night through youtube... As far as I know, this error is because of trying to write in a read only space, and I can't figure out what that means...
You have to check if the value of j
is in range before doing strcmp(astr_list[j], astr_list[j + 1])
, or they may be out-of-range and undefined behavior due to out-of-range access may be invoked.
It should be like this:
while (j >= 0 && strcmp(astr_list[j], astr_list[j + 1]) > 0) {
User contributions licensed under CC BY-SA 3.0