I have tried everything I know but I just can't create the array. Every time the terminal shows "Segmentation fault: 11". Please help, thanks!(details in my comments)
Updated: char*load file(int *numberofwords)
returns reading from txt file(I made it up just to test how my program works):
Have,a.nice day
Bye.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *loadfile(int *counter) {
int i;
char chr;
char *data;
char *junk;
FILE *GENE;
GENE = fopen("hw7codex.txt", "r");
if (GENE == NULL) {
printf("ERROR - Could not open file.\n");
return NULL;
}
while (1) {
fscanf(GENE, "%s", junk);
(*counter)++;
if (feof(GENE)) break;
}
int wholecounter = 0;
while (1) {
fscanf(GENE, "%c", &chr);
wholecounter++;
if (feof(GENE)) break;
}
data = (char *)calloc(wholecounter, sizeof(char));
if (data == NULL) {
printf("ERROR - Could not allocate memory for the file.\n");
return NULL;
}
rewind(GENE);
i = 0;
while (1) {
fscanf(GENE, "%c", &chr);
data[i++] = chr;
if (feof(GENE)) break;
}
fclose(GENE);
return data;
}
int main(void){
int wordscount=0;
char *temp;
//temp gets a long string from a txt file(which looks like
//"Have,a.nice day"then divides it to separate words:"Have","a", "nice","day"
temp = strtok(loadfile(&wordscount)," ,.\n");
//I want to know how many separate words in this txt file
printf("%s\n", loadfile(&wordscount)); //it prints out 5
printf("%d\n", wordscount); //it prints out 'Have,a.nice day\nBye'
//I want to create a string array here to hold all those words , but I keep failing
char array[wordscount][40];
int j=0;
while (temp != NULL){
strcpy(array[j], temp);
j++;
temp = strtok (NULL, " ,.\n");
}
for (j = 0; j < wordscount; j++){
printf("%s\n", array[j]);
}