C:获取用户输入,存储,继续,然后显示最后50个输入

C:获取用户输入,存储,继续,然后显示最后50个输入,c,string,io,copy,C,String,Io,Copy,这就是我如何将我的输入存储到输入中,并希望将其副本存储到输入历史中的方法 #define HISTORY_SIZE 50 #define INPUT_SIZE 512 /*Max input size*/ char input[INPUT_SIZE]; /*Holding user input globaly*/ char* input_history[HISTORY_SIZE]; 但是当我把它打印出来的时候,它就不起作用了 void addToHistory() { /*input

这就是我如何将我的输入存储到输入中,并希望将其副本存储到输入历史中的方法

#define HISTORY_SIZE 50
#define INPUT_SIZE 512   /*Max input size*/
char input[INPUT_SIZE];  /*Holding user input globaly*/
char* input_history[HISTORY_SIZE];
但是当我把它打印出来的时候,它就不起作用了

 void addToHistory()
 {
/*input_history[currentHistorySize++] = strtok(input,"\n");*/
input_history[currentHistorySize++] = input;
printf("ADDEDTOHISTORY: %s \t\t %d \n", input_history[(currentHistorySize- 1)],currentHistorySize);

 }
我已经坐着试着解决这个问题很久了,似乎看不出我哪里出了问题,也许一双新眼睛会注意到一些愚蠢的错误

基本上,我想使用

/*strcpy(input,input_history[currentHistorySize-2]);
printf("LAST INPUT, %s \n %s \n \n", input,input_history[currentHistorySize-2]);*/

printf("0: %s \n ", input_history[0]);
printf("1: %s \n ", input_history[1]);
printf("2: %s \n ", input_history[2]);
然后将其副本存储到char*input\u历史记录中 然后以后可以打印出来

非常简单。

而不是

fgets(input,INPUT_SIZE,stdin)
使用

假设
input\u history
已初始化。

但是,这并不考虑
input
的大小是否小于或等于
input\u history[x]
的容量。这取决于您的检查。

您的
input\u history
变量是一个指针数组,您不能这样分配您的输入:
input\u history[currentHistorySize++]=input

阅读指针:)


然后继续使用C标准库函数之一,例如,
strndup()

这里肯定有一个问题:

sprintf(input_history[currentHistorySize++],"%s",input);
最终,您的所有历史记录都将引用相同的内存位置,即
input

创建一个新的char数组并将输入复制到其中,然后引用新数组。

最可能的问题是,您实际上没有复制字符串,只是复制指针(字符串的地址)。请尝试以下方法:

input_history[currentHistorySize++] = input;
或者可能:

input_history[currentHistorySize] = malloc(strlen(input) + 1);
strcpy(input_history[currentHistorySize], input);
currentHistorySize++;

您还应记住在完成后释放它们。

这是指针分配,而不是字符串副本:

input_history[currentHistorySize] = strdup(input);
导致
input\u历史记录中的所有元素指向
input

您可以使用
strdup()
复制字符串:

input_history[currentHistorySize++] = input;

或者
malloc()
strcpy()
。当不再需要时,记得
free()
input\u history
的元素。

假设input\u history是initialized@UmNyobe当然可以。我在回答中加上了你的便条。谢谢
input_history[currentHistorySize++] = input;
input_history[currentHistorySize++] = strdup(input);