出现错误:Exception throws at 0x79ECFC60 (ucrtbased.dll), INST.exe): 0xC0000005: 访问冲突写入位置 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 了解到指针是什么......据我所知,这个错误是因为试图在只读空间中写入,我无法弄清楚这意味着什么......

麦克猫

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

应该是这样的:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章