简体   繁体   中英

Memory Allocation with 2d Character Array

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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM