Reputation: 47
I recently learned about pointers, and have been working hard to really understand them. However, I have run into trouble. For class we had to write a function that would double an array x amount of times. I was able to write the function without any real problems, but I'm trying to implement it into an actual code and I continue to get invalid pointer errors. Here's the code:
#include <iostream>
using namespace std;
int *ArrayDoubling(int inputArray[], int initialSize, int numberToDouble);
int main(){
int arr[2] = {0,1};
int array_size = 2;
int number = 3;
ArrayDoubling(arr, array_size, number);
}
int *ArrayDoubling(int inputArray[], int initialSize, int numberToDouble){
for(int i=0;i<numberToDouble;i++){
int *array2 = new int[initialSize*2];
for(int i=0;i<initialSize;i++){
array2[i] = inputArray[i];
array2[i+initialSize] = inputArray[i]*2;
}
initialSize = initialSize*2;
delete []inputArray;
inputArray = array2;
}
return inputArray;
}
So what exactly is causing the problem, and how can I fix it? Also not sure if this will actually print the output of the Array, but I'm also trying to get that to happen. Thanks for any and all help!
Upvotes: 1
Views: 1957
Reputation: 10064
The biggest problem with your code is this line: delete []inputArray;
inputArray
was originally declared as int arr[2] = {0,1};
which should not be deleted. You can only delete variables which were created using keyword new
.
Broadly speaking, your program is going to need to look something like this. Note that new[]
happens outside of the population loops in ArrayRepeat
so it is only called once and similarly delete[]
will only be called once, on the same pointer that was created through new[]
.
// dynamically allocate an array which contains the first `N` elements of
// `array` repeated `repeats` times.
int * ArrayRepeat (int * array, size_t N, int repeats) {
int * result = new int[N * repeats];
assert(result); // Error check
// Loops to populate result goes here
return result;
}
int main (void) {
int arr[] = {0, 1};
int * repeated = ArrayRepeat(arr, 2, 3);
// Print the result
for (int i = 0; i < 2 * 3; ++i) {
printf("%d\n", repeated[i]);
}
delete[] (repeated);
return 0;
}
Upvotes: 0
Reputation: 1893
I am not quite sure what your intension is, but I think your second for loop should look like this:
for(int i=0;i<initialSize;i++)
Upvotes: 0
Reputation: 1416
Your inner loop is looping by the number of times to double, not the size of the array. For inputs where the size of the array is less than the number of times to double, you will be accessing out of range indices.
Upvotes: 0
Reputation: 238461
The ArrayDoubling
function calls delete[]
on the inputArray
argument. But you pass a pointer to an automatic array when you call it in main
. Calling delete[]
with a pointer that you didn't get from new[]
has undefined behaviour.
To fix it, only use the function with dynamically allocated arrays.
Upvotes: 3