问题描述
这是我的问题:我正在构建自己的外壳程序并实现了历史记录功能,唯一的问题是历史记录数组只能接受100个值,最后100个值,这意味着当它超过100时,第一个值将被获取删除后,每个值将移回一个索引,最后一个值将排在第100位。我唯一的问题是,无论我如何尝试其余的程序,都开始出现bug(因此注释行)。
这是我的代码:
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为1111,因为我接下来要实现它。
解决方法
- 将有99个移动而不是100个移动,以将100个元素的数组的元素移动1个。省略了最后1步,因为它是将一个元素移出数组。
- 这种转变正在减少一个要素。现在使用
history_counter
作为索引是错误的,因为计数应根据下降而递减。
固定代码为:
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++;
}
或者省略匹配的减量和增量,可以这样写:
else {
for(int j=0;j+1<100;j++){ /* use j+1<100,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
可以写为j<100-1
。使用常量值(也许是宏)而不是幻数100
可以进一步改善代码。