【问题标题】:Building a dictionary建立字典
【发布时间】:2014-05-02 14:55:58
【问题描述】:

我有一个拼贴分配来构建一个动态字典,该分配必须与指针和动态分配一起使用(我知道这是我在这里说的微不足道的东西)。 我一直在尝试使用代码的任何方式,这就是我想出的。 我确定我在这里有错误,我的问题实际上是如何正确实现内存分配,然后如何将单词/定义存储在我分配的内存中。

 printf("Please enter the amount of words in the dictionary.\n");
scanf("%d",&numOfWords);
getchar();
wordsArr = (char***)malloc(3 * sizeof(char**));
for (int i = 0; i < numOfWords; i++)
{
    printf("Please enter the word and how many defenitions it has (1 or 2).\n");
    scanf("%s %d",&wBuffer[i],&defs);
    getchar();
    wordsArr[i]=(char**)malloc(strlen(wBuffer)*sizeof(char*)+1);
    strcpy(*wordsArr[i],wBuffer);
    for (int j = 0; j < defs; j++)
    {
        printf("Enter the %d is:\n",i);
        gets(dBuffer);
        wordsArr[i][j]=(char*)malloc(strlen(dBuffer)*sizeof(char)+1);
        strcpy(wordsArr[i][j],dBuffer);
    }
}
//Dont mind this just for the print test    
for (int i = 0; i < numOfWords; i++)
{
    for (int j = 0; j < defs; j++)
    {
        printf("%s",wordsArr[i][j]);
    }
}

}

【问题讨论】:

  • 为什么不使用哈希表……或者数组列表……或者一些数据结构
  • 老师限制我们不要使用任何类似的东西,只能使用函数、指针、字符串、数组和动态分配,。
  • 有趣的东西。你知道数据结构都可以建立在数组、指针、字符串和动态分配上,但那是我试图把它粘在老师身上的邪恶学生
  • 呵呵,如果我可以使用数据结构,我已经可以得到这个“项目”了,但是因为我不能使用它们,所以我卡住了,上面的代码是我迄今为止唯一能想到的......基本上我需要的是 X 个单词,每个单词都有 1 或 2 个定义 (arr[][][]) prolly。类似的东西。而且我知道上面的代码是一个很大的 WTF,因为它不起作用。
  • 二维数组,第一维为单词编号,第二维为定义编号。您所拥有的大部分内容似乎都是正确的,但不是很有活力。完成后一定要释放分配的内存

标签: c string pointers visual-studio-2012 multidimensional-array


【解决方案1】:

也许试试这个(没有 C 编译器方便)

char ***array;
array = malloc(numOfWords * sizeof(char**));
for (i = 0; i < rows; i++)
   array[i] = malloc(3 * sizeof(char*)); // assumign 2 is your max definitions

这应该将 numOfWords 指针分配到一个字符数组的内存中,其中包含 3 个字符数组,第一个是字典单词,另外两个是定义。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 2018-04-01
    • 1970-01-01
    • 2016-02-03
    • 2016-07-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多