c++ - 抛出异常:访问冲突
问题描述
此函数反转指针数组并将其返回给 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;
}
解决方案
这就是问题:
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;
}
推荐阅读
- javascript - 如何更改渲染的组件?
- python - ModuleNotFoundError:Windows 上没有名为“grp”的模块
- php - VIVVO Lib 框架问题
- r - 带有百分比的堆积条形图
- javascript - 使用 Javascript 在前端创建基本 URL(开发、API 和生产)
- java - 拆分字符串没有给出预期的输出
- python - 用于自动化脚本的 Web 服务
- php - laravel 上的图片上传无法在线工作:Laravel
- python - 在 Google Colab 上为 cpu 和 gpu 获取相同的运行时
- python - 如何仅过滤排列中的唯一对,python?