1

So I need to scan in a dictionary of words, max length 19 and dynamically allocate memory to set the size of the dictionary array. I am stuck on how to do this.

fscanf(ifp, "%d", &numwords); //Number of words in dictionary

char ** dictionary;


for(i = 0; i < numwords; i++){
    for(j = 0; j < 20; j++){
        dictionary[i][j] = (char *) malloc(20 * sizeof(char));
        fscanf(ifp, "%s", &dictionary[i][j]);
        //printf("%s\n", dictionary[i]); //tests that the letter is read in correctly
    }
}

I am lost on what is wrong. Any help would be greatly appreciated.

1
  • This is not a 2D array, but a pointer of pointers. Please read the C FAQ on these things. Commented Oct 12, 2012 at 21:44

1 Answer 1

4

You need to allocate memory to hold the list of char*:

dictionary = malloc(sizeof(char*) * numwords);

and when you are allocating the char array:

dictionary[i] = malloc(20); /* No [j] */

Note that sizeof(char) is guaranteed to be 1 so it can be omitted from the malloc() argument. When reading the strings, prevent buffer overrun by specifying the maximum width allowed:

fscanf(ifp, "%19s", dictionary[i]);

There is no requirement for the inner loop. The program needs to read numwords from the file, only the outer for is required.

Check return values from functions (malloc() does not return NULL for example and fscanf() returns the number of expected assignments).

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

5 Comments

I'd rather use sizeof(*dictionary). Also, you forgot to point out that it's not dictionary[i][j] that needs to be assigned the result of malloc() but only dictionary[i].
So what you are saying is that before the for loops to read in the dictionary I need to put dictionary = malloc(sizeof(char*) * numwords); and that dictionary[i] = malloc(20); goes in the for loops?
Ok so even though it has to be a 2D array it will only need that one loop?
@Ryan, it isn't really 2d array but a list of pointers, but yes just one loop.
The reason I ask is because I need to make a binary search now, requiring a 2d array to access specific letters of the words in the dictionary. Sorry to be such a pain on this, just new with memory allocation

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.