首页 > 解决方案 > 抛出异常:访问冲突

问题描述

此函数反转指针数组并将其返回给 main。主要问题是代码返回抛出异常:读取访问冲突。fptr 为 0xCCCCCCCC。

最小描述

错误的根源可能是什么?

int* mirror(int* p[], int n) {
    int* ptr,* fptr;
    int swap;
    ptr = p[0];
    fptr = p[n-1];
    while (fptr > ptr) {
        swap = *ptr;
        *ptr = *fptr;
        *fptr = swap;
        ptr++;
        fptr--;
    }
    return *p;
}

标签: c++arraysalgorithmpointersreverse

解决方案


这就是问题:

while (fptr > ptr) { ... }

ptr是第一个元素(第一个指针),并且fptr是最后一个元素(最后一个指针),并且您正在遍历数组,而第一个元素小于最后一个元素,但这意味着插入了数组中的元素按地址顺序排列,我认为不是..

相反,您应该使用维度 ( n) 来执行此操作:

int** mirror(int* p[], int n) { // return a pointer to integers pointer, not a pointer to integer
    for(int i = 0; i < n/2 ; i++){ // go through the first half of the array
       int* tmp = p[i];  // and those three lines swap the current and the n - current elements
       p[i] = p[n-i-1];
       p[n] = tmp;
    }
    return p;
}

推荐阅读