This is my implementation of a circular array so far. It is supposed to store the last 5 commands entered, by entering the 6th command in the place of the 5th and discarding the 1st. What I have managed to do so far is, to able to store the 5 commands and print them out. On the 6th command, I noticed that it goes in the 2nd position (k=1
) of the historyArray
, but when debugging, k
was equal to 0
which would at least push the last command at the top. If you can put me in the right track again, I would appreciate it. Here is part of the code.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (int argc, char *argv[])
{
int i=0;
int j=0;
int k=0;
int tempIndex = 0;
int elementCounter = 0;
char inputString[100];
char *result=NULL;
char delims[] = " ";
char historyArray[5][20] = {0};
char tokenArray[20][20] ;
char hCommand[1][20];
do
{
j = 0;
printf("hshell>");
gets(inputString);
//skip writing "history" in historyArray
if (strcmp(inputString,"history")!= 0)
{
strcpy (historyArray[k], inputString);
}
k = (k+1) % 5;
if (elementCounter <= 5)
elementCounter++;
// Break the string into parts
result = strtok(inputString, delims);
while (result!=NULL)
{
strcpy(tokenArray[j], result);
j++;
result= strtok(NULL, delims);
}
if (strcmp(tokenArray[0], "exit") == 0)
return 0;
if (strcmp(tokenArray[0], "history") == 0)
{
if (j>1)
{
tempIndex = atoi(tokenArray[j]);
puts(tempIndex);
}
else
{
for (i=0; i<elementCounter-1;i++)
printf("%i. %s\n", i+1, historyArray[i]);
}
}
else
{
printf("Command not found\n");
}
} while (1);
}
After suggestions (still incomplete):
j = 0;
//elementCounter = 0;
printf("327>");
gets(inputString);
strcpy (historyArray[k], inputString);
k = (k+1) % 5;
if (elementCounter <= 5)
{
elementCounter++;
}
gets
andstrcpy
will lead to overflows. You should investigatefgets
andstrncpy
as "safe" alternatives. – Acidformingif (elementCounter <= 5)
; why do you need that? – Acidformingif (elementCounter <= 5)
is used to count the elements in the array and I used it in the array printing further down the code. It is there so that it does not print more than 5 values. – IndigenouselementCounter
reaches 6? Thenk
will never be updated ever again. – AcidforminghistoryArray[k % 5]
(incrementing k each time around),k + 1
is always the total number of "commands" entered, andMIN(k + 1, 5)
is the number of jobs currently in the array. – Cruiserweightk = (k+1) % 5;
just aboveif (elementCounter <= 5)
but then the value change occurs after position1
– Indigenous