简体   繁体   English

使用2d字符数组的内存分配

[英]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. 所以我需要扫描单词字典,最大长度为19并动态分配内存来设置字典数组的大小。 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* : 您需要分配内存来保存char*列表:

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

and when you are allocating the char array: 当你分配char数组时:

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

Note that sizeof(char) is guaranteed to be 1 so it can be omitted from the malloc() argument. 请注意, sizeof(char)保证为1因此可以从malloc()参数中省略它。 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. 程序需要从文件中读取numwords ,只需要外部for

Check return values from functions ( malloc() does not return NULL for example and fscanf() returns the number of expected assignments). 检查函数的返回值(例如, malloc()不返回NULLfscanf()返回预期赋值的数量)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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