I am making a program that removes a number from the index that the user provides from the array, displays the new array, then asks the user to insert a number at whatever index they choose. The first part of this program works fine when it comes to removing an index, but I am having trouble with adding an index and number. For example, if the NEW array after the user deletes the number from index 5 is: 12 34 45 2 8 16 180 182 22, which is correct if you remember that arrays start at 0, then they request for example index 5 to be added again with the number 78, it gets messed up. It displays 12 34 45 2 78 8 16 180 182 22 (and then it also outputs the number -858993460 for some reason?) SO the problem basically is that it adds the new index and number one index BEFORE it is supposed to. Im sorry if this sounds so confusing but I have been stuck on it for hours. Thank you!
//This program demos basic arrays
#include <iostream>
using namespace std;
const int CAP = 10;
int main()
{
int size;
int list[CAP] = { 12, 34, 45, 2, 8, 10, 16, 180, 182, 22 };
size = 10;
int i, delIndex, addIndex, newInt = 0;
cout << "Your list is: " << endl;
for (i = 0; i < CAP; i++)
{
cout << list[i] << endl;
}
//Deleting an index
cout << "\nPlease enter index to delete from: ";
cin >> delIndex;
for (i = delIndex; i <= 10; i++)
{
list[i] = list[i + 1];
}
cout << "The index position you specified has been deleted." << endl;
cout << "The new array is: " << endl;
for (i = 0; i < (size - 1); i++)
{
cout << list[i] << endl;
}
//Adding an index
cout << "\nNow, please enter the index position to add to: " << endl;
cin >> addIndex;
cout << "\nEnter the number to add to the index: " << endl;
cin >> newInt;
for (i = size - 1; i >= addIndex - 1; i--)
{
list[i + 1] = list[i];
}
list[addIndex - 1] = newInt;
size++;
cout << "The number has been added at the specified index position." <<
endl;
cout << "The new array is: " << endl;
for (i = 0; i < size; i++)
{
cout << list[i] << endl;
}
return 0;
}
for (i = delIndex; i <= 10; i++) {list[i] = list[i + 1];}-- This loop writes to items that are out-of-bounds of the array. Second, arrays cannot be resized, so "removing elements" or "adding elements" is not what you're trying to do.list[9]. You are accessing index 10 and 11, thus creating a buffer overrun and undefined behavior occurs.for (i = delIndex; i <= 10; i++)tofor (i = delIndex; i < 9; i++)for (i = delIndex; i < 10; i++)-- That still writes out of bounds on the last iteration.