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.
This:
Just gives you the static size of the array
stringwhich is an array of 20 pointers and each pointer is 4 bytes, 20 * 4 bytes = 80 that’s why it’s always 80. you already have the size of the array because you incrementifor each string, that’s the size of the array just printiby size I mean the number of strings you allocated in the array, or the number of lines in the file.Edit:
if you want to get the length of the string(s) in the array use
strlenNote:
it should be
intnotfloatbut that’s not the point.