### inserting into the back of an array

hi guys

i am working on creating a priority queue, i seem to have done the algorithm for inserting from the top correctly but the algorithm for inserting from the bottom doesnt seem to work it just overwrites the existing data.

below is my code :

list is an array and listlength is the size of the array declared as a integer

thanks for any help given

 ``123456789101112131415161718192021222324252627282930`` `````` void inserttop(string task) { //int head = 0 ; string temp ; listlength++ ; for (int i = 1; i < listlength; i++) { list[listlength - i] = list[listlength - i - 1] ; } list[0] = task; } void insertbottom(string task) { //int tail = listlength ; string temp ; listlength++ ; for (int i = 0; i <= listlength; i++) { list[listlength - i] = list[listlength] ; } list[listlength] = task; } ``````
> it just overwrites the existing data.
Yep, `list[listlength - i] = list[listlength];`
¿what is your intention with the 24-27 loop?

Also, out of bounds
In you insertbottom, you are indeed over writing everything in your array. It will take everything from the last element in the array to the first and make them all equal to the last. Then after your for-loop is done, you then change the last element in the array to task.

Here is an example code that inserts at the back of the array:

 ``12345678910111213`` ``````int* extend_arr(int arr[], int length, int val) { int* array2 = new int[length + 1]; for (int J = 0; J < length; J++) array2[J] = arr[J]; array2[length] = val; delete[] arr; arr = NULL; return array2; }``````

Note you can change it from int* to string* and it should still do the same thing...I think
Last edited on
Topic archived. No new replies allowed.