我正在做一个学校项目,制作一个使用插入排序对城市名称进行排序的程序。在这样做的时候,出现了这个错误,我找不到合适的答案或解决方案。
#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;
}
我还在学编程,我很困惑。有人能给我一个不太复杂的答案吗?这个项目是由一位离散数学教授完成的,他要求我们搜索任何必要的信息,因为他没有教过这些,我昨晚刚刚通过youtube了解到指针是什么。。。据我所知,这个错误是因为试图在只读空间中写作,我不明白这意味着什么。。。
在执行strcmp(astr_list[j], astr_list[j + 1])
之前,您必须检查j
的值是否在范围内,或者它们可能超出范围,并且可能会调用由于超出范围访问而导致的未定义行为。
应该是这样的:
while (j >= 0 && strcmp(astr_list[j], astr_list[j + 1]) > 0) {