2

I just figured out how to do this with integers so decided to give it a go with strings and got stuck.

Here is what is in my file "kw":

keyword0
keyword1
keyword2
keyword3

With this current code I'm getting "error: format '%s' expects argument of type 'char *', but argument 3 has type 'char **'

#include <stdio.h>

int main () {
    FILE *pFile;

    pFile = fopen("kw", "r");

    if (pFile != NULL) {

        char *a[3];
        int i;

        for(i = 0; i <= 3; i++) {
            fscanf(pFile, "%s", &a[i]);
            printf("%s\n", a[i]);
        }
    }
    return 0;
}

Could someone point me in the right direction here? Thank you.

1 Answer 1

2

There are several problems with this code:

  • You are going through four elements of the array a, while the array has only three elements.
  • You did not allocate space for the strings that you are reading with scanf.
  • You do not pass the address of address when you read strings.

To fix the first problem, change <= for != or <, like this:

for(i = 0; i != 3; i++)

To fix the second and the third problem, use malloc:

a[i] = malloc(21*sizeof(char));
fscanf(pFile, "%20s", a[i]);

Once you are done with the data that you allocated, don't forget to free the strings:

for(i = 0; i != 3; i++) {
    free(a[i]);
}
Sign up to request clarification or add additional context in comments.

2 Comments

actually, the code is fine with "for(i = 0; i <= 3; i++)" that is supposing he fixes the array a to hold 4 elements. But you should probably use "for (i = 0; i < 4; i++)" although it's the performance gain is trivial, it used to be much faster to use "<" over "=". Other than that, the above answer is definitely the way to go.
Just what I needed to know. Thanks a bunch.

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.