出现错误:Exception throw at 0x79ECFC60 (ucrtbased.dll), INST.exe): 0xC0000005: Acsess violation writing location 0xCCCCCCCC

An error appeared : Exception thrown at 0x79ECFC60 (ucrtbased.dll), INST.exe): 0xC0000005: Acsess violation writing location 0xCCCCCCCC

我正在做一个学校项目,制作一个使用插入排序对城市名称进行排序的程序。 执行此操作时,出现此错误,我找不到合适的答案或解决此问题的方法。

#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 了解到指针是什么...... 据我所知,这个错误是因为试图以只读方式写入 space,我无法弄清楚那是什么意思...

您必须在执行 strcmp(astr_list[j], astr_list[j + 1]) 之前检查 j 的值是否在范围内,否则它们可能超出范围并且 未定义的行为 由于超出范围的访问可能会被调用。

应该是这样的:

        while (j >= 0 && strcmp(astr_list[j], astr_list[j + 1]) > 0) {