未知长度字符串的 C 二维数组,访问元素时崩溃

C 2D arrays of string of unknown length, Crashing when accessing the elements

所以我 运行 遇到了这个错误,到目前为止我似乎找不到答案,如果之前有人问过这个问题,我深表歉意。 这是受影响的代码:

char **List_Of_Words;
int List_Index=0;

List_Of_Words = malloc(Number_of_Words *sizeof(char*));

//Processed_Word word is a word that has been read from a file, its in a loop.
strcpy(*List_Of_Words[List_Index], Processed_Word);
List_Index++;


//im looping through the array to print each word thats stored there
 for(int i = 0;i < List_Index; i++)
{
printf("%s\n", *List_Of_Words[List_Index]);
} 

当我使用 Visual Studio 进行调试时,出现此错误:

Unhandled exception at 0x01229240 in Wordcount.exe: 0xC0000005: Access violation writing location 0x00000030.

因此,我假设我的程序正在尝试访问它无权访问的内存。 C 对我来说是一门新语言,所以我真的不知道如何处理这个问题。

你的代码有很多问题。

首先你没有分配足够的内存。 List_Of_Words 需要为每个单词分配足够的内存,您做得很好。但是每个 List_Of_Words[] 也需要分配内存来包含单词。

那么你这样做是错误的,因为你传递的是 char 作为第一个参数而不是 char *

strcpy(*List_Of_Words[List_Index], Processed_Word);

解决这个问题和之前的问题你的代码应该是这样的

List_Of_Words[List_Index]=malloc(strlen(Processed_Word)+1);
strcpy(List_Of_Words[List_Index], Processed_Word);

或者如果可用,您可以使用 strdup 将两行合并为一条

List_Of_Words[List_Index]=strdup(Processed_Word);

你在打印字符串时也重复了 de-referencing 的问题,所以它应该看起来像

printf("%s\n", List_Of_Words[i]);

当然除非你只是打印出第一个字符,在这种情况下你应该使用 %c 格式化代码。

这里的问题是你已经定义了 List_Of_Words 是什么但忘了给它分配内存。

令 r = 您要存储在 List_Of_Words 中的单词总数。

下面的代码行分配 r 个数据类型为 char* 的块,其中每个块将包含一个单词。

char **List_Of_Words = (char **)malloc(r * sizeof(char *));

下面这行代码分配了 c 个数据类型为 char 的块,其中每个块将保存一个字符并将数据存储在其中。这里c是要存储的processed_word的大小。

Inside the loop:
    int c = strlen(processed_word) + 1
    List_Of_Words[i] = (char *)malloc(c * sizeof(char));
    strcpy(List_Of_Words[i], processed_word);

这一行

strcpy(*List_Of_Words[List_Index], Processed_Word);

不会为副本分配内存,它假定您已经分配了足够的 space。如果您的系统有 strdup,您可以使用它来分配和复制字符串(但是,strdup 不可移植 - 它不在 C 标准或 Posix 标准中)。

List_Of_Words[List_Index] = strdup(Processed_Word);

如果没有 strdup,请在执行 strcpy 之前分配内存。

List_of_Words[List_Index] = malloc(strlen(Processed_Word) + 1); // + 1 for the [=12=] at the end
strcpy(List_Of_Words[List_Index], Processed_Word);

另请注意,使用下标与取消引用相同。 List_of_Words[index] 是一个 char* 即它已经是你想要的字符串。 *List_of_Words[index]char 即它是 List_of_Words[index] 处字符串的第一个字符。将 char 视为指针只会导致麻烦。您需要在代码

中每次使用 *List_of_Words[...] 时删除 * 前缀

你说“//Processed_Word 单词是从文件中读取的单词,它在一个循环中。” - 希望你没有在循环中使用 List_of_Words malloc。我希望您在读取单词一次的循环之外进行此操作

此外,我希望您为 List_of_Words 中的每个条目分配内存,但您似乎没有这样做。

类似于您尝试创建的二维数组实际上是一个一维数组(一维),其中包含对其他一维数组(第二维)的引用。内容单元格存在于其他一维数组中(如果有多个,则为最后一个维度的数组)。