Hello all, firstly I'm happy to join this forum, secondly, I need some help. I'm trying to write a hangman game in c but I cannot for the life of me get my array filled properly. Here is the code so far:
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <getopt.h>
char *dict = "/usr/dict/words";
int numGuess = 10;
void dictAtrb()
{
FILE *dictFile;
char c;
int words = 0, max = 0, current = -1;
if((dictFile = fopen(dict,"r")) == NULL)
{
printf("Could not load dictionary");
exit (1);
}
while(c!=EOF)
{
c = fgetc(dictFile);
if(c == '\n')
{
words++;
if(current > max)
{
max = current;
}
current = -1;
}
else
{
current++;
}
}
fclose(dictFile);
printf("%d words with max length %d\n",words,max);
}
void buildDict()
{
FILE *dictFile;
char tempArray[BUFSIZ];
char dictArray[6];
char *p;
int i = 0, count = 0, maxCount = 6;
if((dictFile = fopen(dict,"r")) == NULL)
{
printf("Could not load dictionary");
exit (1);
}
while(fgets(tempArray, BUFSIZ, dictFile) != NULL)
{
if((p = strchr(tempArray, '\n')) != NULL)
{
*p = '\0';
}
if(count == maxCount)
{
break;
}
strcpy(dictArray[count], tempArray);
count++;
}
for(i; i < count; i++)
{
printf("%s\n", dictArray[i]);
}
fclose(dictFile);
}
int main( int argc, char* argv[] )
{
srand(time(NULL));
if(argc > 1)
{
char c;
while ((c = getopt(argc, argv, "g:s:f:n")) != -1)
{
switch(c)
{
case 'g':
numGuess = atoi(optarg);
break;
case 's':
srand(atoi(optarg));
break;
case 'f':
dict = optarg;
break;
/*case 'n':*/
default:
printf("Invalid argument. Use -g, -s, -f or -n\n");
break;
}
}
}
/*display welcome*/
printf("\nWelcome to Hangman\n");
printf("-\n");
/*display random seed*/
printf("Random seed was %d\n",rand());
/*load and display dictionary*/
printf("Load dictionary from file: %s\n",dict);
dictAtrb();
buildDict();
return 0;
}
My issues occur in the buildDict function, where I am trying to read words from a text file into an array. I'm currently using an array of size 6 to work with my test dictionary of 6 words, before I try to make it dynamically create it's own size. I realise this could probably be done by passing in the "words" value from the dictAtrb function but I'm not too hot on this and so not too sure how to do this.
When I compile the code I get:
hangman.c: In function 'buildDict':
hangman.c:69: warning: passing arg 1 of 'strcopy' makes pointer from integer without a cast
When I run it, it crashes with a segmentation fault