I am working on a class project and I really need help. What I need to realize is to read two string from either one text file, or two separate files, and store them in two arrays respectively. The strings can be of any length, but do not have to be very long. The size of each array can be adjusted automatically according to the length of the corresponding string.
I've searched on Stack Overflow and got some codes, I was trying one which uses malloc(). But I had troubles when I was trying to get the size of the array.
int main(){
int i = 0;
int BUFSIZE = 1000;
char* string[20];
FILE *fp = fopen("input.txt", "r");
if (fp == 0){
fprintf(stderr, "Error while opening");
return 0;
}
string[i] = (char *)malloc(BUFSIZE);
while (fgets(string[i], BUFSIZE, fp)) {
i++;
string[i] = (char *)malloc(BUFSIZE);
}
float len=sizeof(string);
printf("%f", len);
int x;
for(x = 0; x<i; x++)
free(string[x]);
scanf("%d", x);
fclose(fp);
return 0;
}
I tried to output len, but I got a constant value 80, no matter how long the string is. Besides, I don't know how to read two strings, and store them in two separate arrays. I got errors when trying to add another string into the codes.