我一直在努力用 C 构建一个简单的 shell。我想添加一个内置函数的历史记录,但我需要知道如何执行以下操作:
我有一个全局变量 commanHistory,我相信它是一个指向字符数组的指针? (如果我错了请纠正我)。
char *commandHistory[MAX_COMMANDS][MAX_LINE_LENGTH + 1];
在我的读取行函数中,我想将第 i 行存储在 commandHistory 的第 i 行中。这是我正在做的:
char *lsh_read_line(void)
{
int bufsize = MAX_LINE_LENGTH;
int position = 0;
char *buffer = malloc(sizeof(char) * bufsize);
int c;
int i = 0;
if (!buffer) {
fprintf(stderr, "lsh: allocation error\n");
exit(EXIT_FAILURE);
}
while (1) {
// Read a character
c = getchar();
// If we hit EOF, replace it with a null character and return.
if (c == EOF || c == '\n') {
buffer[position] = '\0';
return buffer;
} else {
buffer[position] = c;
}
position++;
// If we have exceeded the buffer, reallocate.
if (position >= bufsize) {
bufsize += MAX_LINE_LENGTH;
buffer = realloc(buffer, bufsize);
if (!buffer) {
fprintf(stderr, "lsh: allocation error\n");
exit(EXIT_FAILURE);
}
}
}
commandHistory[i++][0] = buffer; // wanting to store command i in commandHistory (also only want to keep track of 10 at a time)
}
当我调用我的内置函数时,我只打印出 10(空):
int lsh_history(char **args)
{
int i;
for (i = 0; i < MAX_COMMANDS; i++) {
printf(" %s\n", commandHistory[i][0]);
}
}
编辑:我需要使用二维数组。这是构建我遇到问题的 shell 的最后一部分。虽然我相信这可以用一维数组来完成,但我遵循这部分说明:
Internally, your shell should save the command history in a 2-dimensional array: char commandHistory[MAX_COMMANDS][MAX_LINE_LENGTH + 1]; Each row of this table will store one command. Viewing the rows arranged in a circle, a data structure similar to a queue can be constructed. Unlike a traditional queue, your command history will never overflow — as we continue to add commands, older commands will simply be overwritten.
最佳答案
你的 commandHistory
实际上是字符串/字符指针的二维数组,而您需要的是一维数组。你应该这样声明:
char *commandHistory[MAX_COMMANDS];
此时您无需担心字符串长度,因为每个命令都是动态分配的。然后访问i
这个数组中的第 'th 个字符串你只需要 commandHistory[i]
, 类型为 char *
.
更新:
如果你(或导师)坚持要commandHistory
声明为静态二维数组:
char commandHistory[MAX_COMMANDS][MAX_LINE_LENGTH + 1];
你不应该像你那样动态分配缓冲区,而是复制命令到你的静态预分配数组中的相应位置commandHistory
(即代替 buffer[position]=..
做 commandHistory[i][position] = ...
)。
关于c - 将值添加到 char* [][],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29478840/