-
Here is readCommandLine
Code:
char * readCommandLine()
{
char command[100];
char *p;
char *q;
char *input;
int i;
fgets( command, sizeof( command ), stdin );
if ((p = strchr(command, '\n')) != NULL)
*p = '\0';
input = command;
i=0;
while (input[i] != '\0')
{
history[historyCount][i] = input[i];
i++;
}
history[historyCount][i] = ' ';
historyCount++;
return(input);
}
Thank you again
-
You're returning a pointer to a local variable (which ceases to exist at the point you return)
Disguising it as
input = command;
doesn't help
This would be a quick fix
static char command[100];
A better fix would be to pass the command array as a parameter, then you don't have to worry about allocating it locally
-
Also, your history[] array isn't being nul terminated, so you won't be able to use it as a string.
-
When I delcare command as static it hangs my program..... It appears to hang on the fgets. If I put a printf before it it will print but if I put one after it, it won't get there. Any Ideas?
here is my edited code:
Code:
char * readCommandLine()
{
static char command[100];
char *p;
char *q;
char *input;
int i;
fgets( command, sizeof( command ), stdin );
if ((p = strchr(command, '\n')) != NULL)
*p = '\0';
//input = command;
i=0;
while (command[i] != '\0')
{
history[historyCount][i] = command[i];
commandLine[i] = command[i];
i++;
}
history[historyCount][i] = ' ';
historyCount++;
return command;
}
Thank you.
-
Here's a working version for you:
Code:
#include <stdio.h>
#include <string.h>
char history[100][100];
int historyCount;
char *readCommandLine(void)
{
static char command[100];
char *p;
if (fgets( command, sizeof( command ), stdin ))
{
if ((p = strchr(command, '\n')) != NULL)
{
*p = '\0';
}
strcpy(history[historyCount], command);
historyCount++;
return command;
}
return NULL;
}
int main(void)
{
char *cmdLine;
int i;
while ((cmdLine = readCommandLine()) != NULL && strcmp(cmdLine, "quit") != 0)
{
printf ("You entered command: >%s<\n", cmdLine);
}
for (i = 0; i < historyCount; i++)
{
printf ("Command history %d >%s<\n", i, history[i]);
}
return 0;
}
/*
Output:
this is a command
You entered command: >this is a command<
blah blah
You entered command: >blah blah<
quit
Command history 0 >this is a command<
Command history 1 >blah blah<
Command history 2 >quit<
*/