我正在编写一个获取整数数组及其逻辑大小的程序。调用时,它会创建一个新数组,其中仅包含数组中的正数。
现在,为了做到这一点,我需要编写一个带有以下参数的 void 类型函数:
(int* arr, int arrSize, int** outPosArrPtr, int* outPosArrSizePTR)
我应该使用指针int** outPosArrPtr来更新包含正数的数组的基地址,并使用指针outPosArrSizePtr来更新数组的逻辑大小。
现在,当我在 xcode 编译器上运行我的代码时,逻辑大小会更新为一个非常大的数字。因此,当我尝试使用在线 gdb 编译器运行程序时,我收到错误“分段错误”。
通过阅读分段错误意味着什么,我了解到这意味着我正在尝试访问“不属于我”的内存或不在调用堆栈或程序堆部分中的内存。
我试图通过查看是否引用了任何空指针或查看是否引用了任何悬空指针来调试我的代码,但似乎问题出在另一个问题上。
我的代码:
#include <iostream>
typedef int* IntArrPtr;
using namespace std;
int main() {
int arrSize;
int *ptrSize;
ptrSize = &arrSize;
cout << "How many integers will this array hold:\n ";
cin >> arrSize;
IntArrPtr a;
a = new int[arrSize];
fillArr(a, arrSize);
getPosNums4(a, arrSize,&a, ptrSize);
cout << "The new size in main is: " << arrSize << endl;
cout <<"The new array with positive integers is:\n";
/*for(int i =0; i<arrSize;i++) // this runs for a large size of arrSize
cout<< a[i] << " ";
cout<<endl; */
return 0;
}
void fillArr(int a[], int size){
cout << "Please enter " << size << " Integers separated by spaces\n";
cout << "Press enter when finished >\n";
int i;
for (i=0;i<size;i++)
cin >> a[i];
}
void getPosNums4(int* arr, int arrSize, int** outPosArrPtr,int* outPosArrSizePtr){
IntArrPtr newArr;
newArr = new int[arrSize];
int i;
int newIndx = 0;
outPosArrSizePtr = &newIndx;//initiliaze the pointer.
for(i=0;i<arrSize;i++){
if(arr[i] > 0){
newArr[newIndx] =arr[i];
newIndx++;
}
}
arrSize = newIndx;
*outPosArrSizePtr = arrSize;
cout << "The new size is of *outPosArrSizeptr is: " << *outPosArrSizePtr << endl;
for(int j=0;j<newIndx;j++)
outPosArrPtr[j] = &newArr[j];
delete []newArr;
newArr = NULL;
for(int i=0;i<newIndx;i++)
arr[i] = *outPosArrPtr[i];
}
一个例子当我在 Xcode 上运行这个程序时:
How many integers will this array hold:
6
Please enter 6 Integers separated by spaces
Press enter when finished >
3 -1 -3 0 6 4
The new size is of *outPosArrSizeptr is: 3
The new array with positive integers is:
The new size in main is: 7445512
The program ended with exit code: 0