我正在设置指针,如上面的代码中所示.问题是无论我尝试过什么,malloc都会抛出一个分段错误.这是代码:
wchar_t **Words ;
int lc = lineCounter() ;
**Words = malloc( lc * sizeof(int) ) ;
if (**Words == NULL) return -1 ;
Run Code Online (Sandbox Code Playgroud)
lineCounter函数只是一个返回文件中行数的函数.所以我尝试做的是释放一些内存,将指针保存到lc个单词.
以下是我的想法:

让我逐行解释你的代码:
wchar_t **Words ;
Run Code Online (Sandbox Code Playgroud)
它正在创建一个指向wchar_t上指针的指针.问题是,在创建时它指向内存中的随机区域,因此它可能不属于您.
*Words = malloc( lc * sizeof(int) ) ;
Run Code Online (Sandbox Code Playgroud)
此行取消引用指针并修改其内容.您正在尝试修改不属于您的内存区域.
我想你想做的是:
wchar_t **Words ;
int lc = lineCounter() ;
Words = malloc( lc * sizeof(wchar_t *) ) ;
if (Words == NULL) return -1 ;
Run Code Online (Sandbox Code Playgroud)
然后malloc你的数组中的所有维度.
编辑:
您可能希望执行类似的操作以符合您的方案:
wchar_t **Words ;
int i = 0;
int lc = lineCounter() ;
Words = malloc( lc * sizeof(wchar_t *) ) ;
if (Words == NULL) return -1 ;
while (i < lc)
{
Words[i] = malloc(size_of_a_line * sizeof(wchar_t));
if (words[i] == NULL) return -1;
++i;
}
Run Code Online (Sandbox Code Playgroud)