I need to write a code segment to do the following:
1. Define a dynamic array to hold 10 integers
2. Read values into the array (use a pointer to access the elements of the array)
3. Print the elemenets of the array in reverse order (use a pointer to access the elements of the array)
It is not outputting what I need. I get an error: pointer being freed was not allocated
Here is what I have so far, any help or suggestions would be appreciated.
The issue is inside the loop, lines 13-17. Inside of that loop you are try to delete a non-null pointer multiple times, resulting in the error you are getting.
To fix this issue you should release pt's memory after you are sure that you are no longer using it's memory. However, in your loop you are deleting pt even though it is clear you are going to be using it. In this case, delete pt at the end of main, after the loop, as it will no longer be used afterward.
#include <iostream>
usingnamespace std;
int main()
{
int *pt = newint[10];
int i;
for(i = 0; i < 10; i++)
{
cout << "Enter number: ";
cin >> *(pt + i);
}
cout << "The numbers in reverse order are: " << endl;
for (i = 10; i < 10; i--) //you still need to implement this logic
{
cout << pt[i] << ", " << endl;
}
delete[] pt; //delete pt and free the memory after all work is done using it.
return(0);
}
After testing your program you are missing header file "<iostresm>". "cout", "cin" and "endl" all needed to be qualified with "std" "delete"needs to be moved outside the for loop just before return.
There does seem to be an extra number I have not figured out yet. I will have to put that in my IDE and test it.
Yes, the first number is because pt[10] is outside the bounds of the array. Arrays along with some others start their indexing at 0. This means the highest index for the array would be 9 not 10.
Starting the second for loop at 9 works properly.
Other than the second for loop starting at 10 everything is the way it should be and works.