3

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.

0

2 Answers 2

2

This:

float len=sizeof(string);

Just gives you the static size of the array string which 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 increment i for each string, that's the size of the array just print i by 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 strlen

while (fgets(string[i], BUFSIZE, fp)) {
    i++;
    len+=strlen(string[i]);
    string[i] = (char *)malloc(BUFSIZE);    
} 

Note: it should be int not float but that's not the point.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, but I got 1 when I printed i, what is the problem?
@phil there's one line in the file ?
yeah, so i represents the number of lines? The string is written in one line in the file, and I have to get the length of the string itself, but I really don't know how...
@phil also, your really should read more about C, check The C Programming Language by K&R
1

If you want the length of the string, then you need to use

strlen(string[i]);

What you are doing will simply return the size of string, which is indeed 80 (20*4).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.