自己的C Shell历史

时间:2013-04-16 11:48:26

标签: c segmentation-fault

我正在编写自己的C Shell,但我在实现维护命令历史方面遇到了麻烦。 我想将它存储在一个带有整数和字符串的结构中(所以我可以将命令及其位置保存在内存中),我只想存储20个元素。

我尝试过使用其他人在本网站上提出的问题的代码,但是当我编译它时,它只会返回一个分段错误,所以我猜测指针有问题。

以下是我发现的与历史相关的所有代码:

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很无用,所以非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

您可以使用链接列表来实现历史记录,始终在头部添加当前命令。像这样:

#include <stdio.h>

typedef struct history
{
    char *ent;
    struct history * next;
}hist;

hist *top = NULL;

void add(char *s)
{
    hist *h =  (hist *) malloc(sizeof(hist));
    h->ent = s;
    h->next = top;
    top = h;
}

void print()
{
    hist *i;
    for (i = top; i != NULL; i = i->next)
        printf("%s\n", i->ent);
}

int main()
{
    add("command");
    print();
}