Hi everybody, I am new to this forum so I apologize in advance for any mistake.
Here is my problem:
I am writting a code in C that reads words from a txt document and puts them in an array. I don't know the number of the words so the size of the array must be dynamic. So I use the command calloc. The problem I think comes from the fact that I make a new type of element named word in order to make the size of the elements of the dynamic array word byte long. Here is my code:
Code:
#include <stdio.h>
#define IN 1
#define OUT 0
main() {
int nc, nw, state;
char c;
FILE *fp;
int i, n;
char * DAT;
typedef char word[20];
state = OUT;
fp = fopen("C:naasas.txt", "r");
nw = nc = 0;
while (fscanf(fp, "%c", &c) && !feof(fp)) {
++nc;
if(c == ' ' || c == '\n' || c == '\t') {
state = OUT;
}
else if(state == OUT) {
state = IN;
++nw;
}
if(c == EOF) {
printf("the end\n");
}
}
fclose (fp);
printf("%d %d\n", nc, nw);
fp = fopen("C:naasas.txt", "r");
DAT = (char*) calloc (nw, sizeof(word));
if (DAT == NULL) {
printf("XXXXX");
}
else {
printf("YYYYYY");
for (i = 0; i <= nw-1; i++) {
fscanf(fp, "%s", &DAT[i]);
}
}
fclose (fp);
for (i = 0; i <= nw-1; i++) {
printf("%s \n", DAT[i]);
}
system("PAUSE");
return 0;
}
I would appreciate it if you can tell me my mistake and help me fix it. I am using Dev-C++ on windows 7.
Thank you in advance