0
我正在編寫自己的C Shell,並且在執行某些事情以維護命令歷史時遇到問題。 我想將它存儲在一個整數和字符串結構(所以我可以保持命令和它的地方一起),我只想存儲20個元素。自己的C Shell中的歷史記錄
我試過使用其他人在本網站上提出的問題中的代碼,但是當我編譯它時,它只是返回一個分段錯誤,所以我猜測指針有什麼問題。
這裏就是我發現歷史有關的代碼:
char** cmdHistory; /* command history - no longer than 20 elements & null terminated */
int historySize = 0;
void addToHistory(char* newEntry) {
char** h;
int historySize = 0;
while (*cmdHistory != NULL)
if (sizeof(cmdHistory) == 20) {
char** newPtr = ++cmdHistory;
free(cmdHistory[0]);
cmdHistory = newPtr;
h = (char**)realloc(cmdHistory,20*sizeof(int));
cmdHistory = h;
cmdHistory[20] = newEntry;
} else {
h = (char**)realloc(cmdHistory,sizeof(int)+sizeof(cmdHistory));
cmdHistory = h;
cmdHistory[historySize] = newEntry;
++historySize;
}
}
void printHistory() {
char** currCmd = cmdHistory;
printf("\n\n");
while (*currCmd != NULL) {
printf("%s\n", *currCmd);
currCmd++;
}
printf("\n\n");
}
int main() {
cmdHistory[20] = NULL; /* null terminate the history */
}
我使用C好看不中用,所以任何的幫助深表感謝。
「我正在編寫自己的C shell」你的意思是你正在編寫一個B shell或者C shell嗎?如果後者...爲什麼? –
使用libreadline,它自動保存歷史記錄並提供對自定義完成的支持。 – LtWorf
代碼很奇怪。例如,我不確定爲什麼要重新分配表格,因爲如果表格應具有固定大小,請添加新元素。整個事情對我來說看起來很可疑,無論你在哪裏找到你正在使用的代碼,我都會去其他地方看看。至於爲什麼它會出現段錯誤,你可以將cmdHistory定義爲一個char **指針,並且首先不需要初始化它,在main中設置「cmdHistory [20] = NULL;」在執行cmdHistory [20]之前,需要初始化和分配cmdHistory。在終止已知長度的數組中也沒有意義。 –