You can't compute strlen(argv[1])
in the initialization of n
before making sure that argc == 2
.
Also, char KeyWord[i]
is wrong: since i
is 0, you are not allocating space for anything. This should at least yield a warning when you compile it, since array sizes must be greater than 0. If you want dynamic allocation, which your comment suggests, you should use malloc
after computing the string's length.
The code should be:
int i = 0, n;
char *KeyWord;
// make sure command line has 2 arguments
if (2 != argc)
{
printf("argc != 2. Try again\n");
return 1;
}
n = strlen(argv[1]);
KeyWord = malloc(n+1);
/* ... */