我正在構建一個shell歷史函數以接收字符串並在程序運行時將其添加到字符串數組中。爲什麼我的數組的前一個元素髮生了變化(C中的字符串數組)
我的問題是,無論何時我用一個新行(字符串)更新數組緩存中的前一個元素將被我的CWD(當前工作目錄)填充,但我需要保留先前設置的字符串。
這是我的主循環得到的字符串,並試圖以存儲與高速緩存功能的歷史:
//prints out the cwd; then loops to take in the line, split it up into arguments, and attempt to execute it
//while lsh_execute returns 0, then frees up the allocated space
void lsh_loop(void)
{
char *line; //pointer to a char (the beg. of an array of chars)
char *cache[10] = {NULL}; //history array
char **args; //pointer to a pointer of a char...
int status, counter = 0, i, j;
do {
printf("%s>", getcwd(0,0)); //print cwd
line = lsh_read_line(); //call read line
counter = lsh_cache_line(counter,line, cache);
printf("This is counter:%i\n", counter);
for(i=0; i<10; i++){
printf("This is cache[%i]:%s\n", i, cache[i]);
}
args = lsh_split_line(line); //split line
status = lsh_execute(args); //execute the split args
free(line); //free memory
free(args);
} while (status); //continue as long as execute returns 1
}
在這個函數中,我複製輸入字符串行字符串數組:
int lsh_cache_line(int counter,char *line, char *cache[10]){
(cache[counter]) = line;
printf("This is cache[%i]:%s\n", counter, cache[counter]);
counter++;
counter = counter % 10;
return counter;
}
這是我的程序的輸出:
[email protected]:~/Desktop$ gcc shell.c
[email protected]:~/Desktop$ ./a.out
/home/paul/Desktop>HI
This is cache[0]:HI
This is counter:1
This is cache[0]:HI
This is cache[1]:(null)
This is cache[2]:(null)
This is cache[3]:(null)
This is cache[4]:(null)
This is cache[5]:(null)
This is cache[6]:(null)
This is cache[7]:(null)
This is cache[8]:(null)
This is cache[9]:(null)
lsh: No such file or directory
/home/paul/Desktop>this is my problem
This is cache[1]:this is my problem
This is counter:2
This is cache[0]:/home/paul/Desktop
This is cache[1]:this is my problem
This is cache[2]:(null)
This is cache[3]:(null)
This is cache[4]:(null)
This is cache[5]:(null)
This is cache[6]:(null)
This is cache[7]:(null)
This is cache[8]:(null)
This is cache[9]:(null)
lsh: No such file or directory
/home/paul/Desktop>it overwrites my previous string with the cwd
This is cache[2]:it overwrites my previous string with the cwd
This is counter:3
This is cache[0]:/home/paul/Desktop
This is cache[1]:/home/paul/Desktop
This is cache[2]:it overwrites my previous string with the cwd
This is cache[3]:(null)
This is cache[4]:(null)
This is cache[5]:(null)
This is cache[6]:(null)
This is cache[7]:(null)
This is cache[8]:(null)
This is cache[9]:(null)
lsh: No such file or directory
/home/paul/Desktop>^C
[email protected]:~/Desktop$
我已經嘗試用不同的方式來聲明和初始化字符串數組,但是這種方式似乎工作得最好。
我在做什麼錯?
可能是一些未定義的行爲。編譯所有警告和調試信息('gcc -Wall -Wextra -g')。然後使用調試器('gdb')以及可能的觀察點。 –