该程序逐行将文本文件读入字符串数组.我无法理解代码中两行的含义:
char **words = (char **)malloc(sizeof(char*)*lines_allocated);
...
words = (char **)realloc(words,sizeof(char*)*new_size);
...
Run Code Online (Sandbox Code Playgroud)
你能帮我理解一下吗?
char **words = (char **)malloc(sizeof(char*)*lines_allocated);
Run Code Online (Sandbox Code Playgroud)
分配lines_allocated指针.当您使用指针指针时,您需要为指针分配空间,并为每个指针分配空间,为您的数据分配空间,在本例中为a char *.
words = (char **)realloc(words,sizeof(char*)*new_size);
Run Code Online (Sandbox Code Playgroud)
这会改变缓冲区的大小,因为在读取文件之前未知行数,然后需要增加分配的指针数.
words指向将lines_allocated在第一时刻存储指针的块,然后new_size在需要时将其增加.
在您的代码中,您还有一行如下:
/* Allocate space for the next line */
words[i] = malloc(max_line_len);
Run Code Online (Sandbox Code Playgroud)
这将分别分配每个字符串.
另外,不要强制转换malloc的结果: