punddalinni punddalinni - 2 months ago 7
C++ Question

Shifting every element in C++ array to the left

I'm trying to write a function delete an element in a C++ array, that is, shift every element one to the left, starting at the index.

The code

#include <iostream>

using namespace std;

const int MAX_SIZE = 50;

void fill_array(char array[], int &current_size, const int max_size);

void print_array(const char array[], const int current_size);

int delete_index(char array[], int &current_size, int index);

int main () {

char array[MAX_SIZE] = {' '};
int current_size = 0;
fill_array(array, current_size, MAX_SIZE);
int index = 4;
delete_index(array, current_size, index);
cout << "After deleting element at index " << index << " the array is: ";
print_array(array, current_size);

return 0;
}

int delete_index(char array[], int &current_size, int index) {
// Check input
if (index > current_size) {
cout << "Index must be between 0 and " << current_size - 1 << endl;
return -1;
}
for (int i = index; i < current_size; i++) {
cout << "array[" << index << "] = " << index << endl;
array[index] = array[index + 1];
}
current_size--;
cout << current_size << endl;
return 0;
}


However, the output I get when inputting "thisisnotworking" and index 4 is:

Please input characters for the array (max of 50) or enter '*' to quit:
onetwothree*
array[4] = 4
array[4] = 4
array[4] = 4
array[4] = 4
array[4] = 4
array[4] = 4
array[4] = 4
10
After deleting element at index 4 the array is: onetoothre


I don't understand it is not increasing the index in the for loop.

I've read similar questions here and elsewhere but couldn't fix the problem still. Any idea why this is?

NOTE: I only want to use arrays (not vectors, etc.).

Answer
    for (int i = index; i < current_size; i++) {
    cout << "array[" << index << "] = " << index << endl;
    array[index] = array[index + 1];
    }

Your loop counter is i. Inside your loop, you should use i instead of index

Corrected:

    for (int i = index; i < current_size; i++) {
    cout << "array[" << i << "] = " << array[i] << endl;
    array[i] = array[i + 1];
    }