Looking forward to help…I need to read two strings from text files and store them into two separate arrays. I’ve searched, and got many codes, one of which worked, so I tried to modify it to read two strings. Here is my code:
int main(){
int i = 0;
int BUFSIZE = 1000;
char* words[20];
char* words2[20];
FILE *fp = fopen("input1.txt", "r");
FILE *fp2 = fopen("input2.txt", "r");
if (fp == 0){
fprintf(stderr, "Error while opening");
return 0;
}
words[i] = (char*)malloc(BUFSIZE);
words2[i] = (char*)malloc(BUFSIZE);
while (fgets(words[i], BUFSIZE, fp)) {
i++;
words[i] = (char*)malloc(BUFSIZE);
}
while (fgets(words2[i], BUFSIZE, fp2)) {
i++;
words2[i] = (char*)malloc(BUFSIZE);
}
printf("Output: \n");
srand(time(NULL));
int j = rand()%i;
int k = (j+1)%i;
fflush(stdout);
printf("%d - %s %d -%s", j, words[j], k, words[k]);
int x;
for(x = 0; x<i; x++)
free(words[x]);
free(words2[x]);
scanf("%d", x);
fclose(fp);
fclose(fp2);
return 0;
}
But it won’t work.Anyone knows why? Thank you!
Reset i = 0 before second loop and enbrace your free(x) code in curly braces