Issue
here is my problem: I am building my own shell and I implemented a history function, only problem is that the history array can only take 100 values, the last 100 values which means that when it goes over 100 the first value gets removed, every value moves back one index and the last value gets the 100th place. My only problem is that whatever I try the rest of my program starts bugging ( hence the commented lines ) Any way to make this work?
Here is my code:
void hist_add(const char *cmd)
{
if(history_counter<100){
strcpy(history_array[history_counter].command_stored, cmd);
history_array[history_counter].command_number = 1111;
history_counter++;
}
// else {
// for(int j=0;j<100;j++){
// strcpy(history_array[j].command_stored, history_array[j+1].command_stored);
// }
// strcpy(history_array[history_counter].command_stored, cmd);
// history_array[history_counter].command_number = 1111;
// history_counter++;
// }
}
P.S: command_number is 1111 for every command so far because I'm implementing it next.
Solution
- There will be 99 moves, not 100 moves, to shift elements of 100-element array by one. The last 1 move is omitted because it is putting one element to out of the array.
- The shift is dropping one element. now using
history_counter
as index is wrong because the count should be decremented according to the drop.
Fixed code is:
else {
for(int j=0;j+1<100;j++){ /* use j+1<100, not j<100, to avoid out-of-range access */
strcpy(history_array[j].command_stored, history_array[j+1].command_stored);
}
history_counter--; /* decrement history_counter according to the drop */
strcpy(history_array[history_counter].command_stored, cmd);
history_array[history_counter].command_number = 1111;
history_counter++;
}
Or omitting matching decrement and increment, it can be written like this:
else {
for(int j=0;j+1<100;j++){ /* use j+1<100, not j<100, to avoid out-of-range access */
strcpy(history_array[j].command_stored, history_array[j+1].command_stored);
}
/* use history_counter-1 instead of history_counter */
strcpy(history_array[history_counter-1].command_stored, cmd);
history_array[history_counter-1].command_number = 1111;
}
j+1<100
can be written as j<100-1
. Using constant value (maybe macro) instead of the magic number 100
will improve your code more.
Answered By - MikeCAT