【问题标题】:How to allocate, initialize, and reallocate an array of pointers to char?如何分配、初始化和重新分配指向 char 的指针数组?
【发布时间】:2014-02-18 13:44:50
【问题描述】:

我一直在尝试制作一个搜索结果列表,如果它需要更多空间,请重新分配它。 我的实现几乎可以工作,但我不知道如何调整数组大小以容纳更多字符串。

原文: char *searchResults[maxResults];

当找到命中时,另一个函数会将每个 searchResults[i] 分配到适当的大小。这是几个搜索结果的样子:

searchResults[0] = "Result"
searchResults[1] = "AnotherResult"
searchResults[2] = "Someresulthere"
searchResults[3] = "TheFourthresult"
searchResults[4] = "YetAnotherOne"

在空间不足时尝试重新分配它并失败后,我转向互联网,显然您无法调整数组大小。幸运的是,或者我想我的时候,有几个网站说要这样做:

char **searchResults;

//initialize result list
searchResults = (char **) malloc( maxResults * sizeof(char *) ) ;
for (i = 0; i < maxResults; i++) {
searchResults[i] = NULL ;

嗯,这似乎根本不起作用。我花了几个小时试图弄清楚这一点,现在我只是受阻了。它将为 searchResults 分配 400 个字节(maxResults 为 100),并且 searchResults[i] 的地址更改了 4 个字节,但没有任何反应。如果我 malloc(100) 到 searchResults[i],它似乎分配了空间,但我似乎仍然无法存储任何东西,除了 searchresult[0] 处的一个结果。

查看 searchResults 时,它总是如下所示:

searchResults[0] = "someResult"

而第一个示例是它的外观。我在想我做错了什么,但我不知道是什么。

谢谢

编辑:如果您投反对票,您至少可以礼貌地说明原因,以便我可以澄清您的不和谐点。

无论如何,这是显示问题的图像。除了第一个元素,我似乎无法分配任何结果,我不知道为什么。

【问题讨论】:

  • 您的malloc 代码很好(除了不必要的转换和缺少错误检查)。很明显你有问题。 SSCCE 可以让我们找到问题所在。说“它不起作用”从来都不是什么好话。
  • searchResults[i] = (char*)malloc(100) so ,strcpy(searchResults[0], "DDDDDDDDDD");(或使用 strncpy)而不是 searchResults[0] = "DDDDDDDDDD"

标签: c arrays string pointers malloc


【解决方案1】:

好吧,我删除了项目,重新制作了它,注释掉了为每个指针分配值,它的工作方式与现在完全一样。问题是什么?不知道,我猜是损坏的项目。

附带说明,Visual Studio 不会在调试器中显示使用 char **searchResults 方法存储的各种指针的值。

【讨论】:

    【解决方案2】:

    要了解如何在数组已满后增加其大小 请正确阅读realloc 函数的工作原理。 我认为正确使用realloc 应该可以解决您的问题。

    例子:

    #include <stdio.h>
    #include <stdlib.h>
    
    int main()
    {
       char *str;
    
       /* Initial memory allocation */
       str = (char *) malloc(15);
       strcpy(str, "tutorialspoint");
       printf("String = %s,  Address = %u\n", str, str);
    
       /* Reallocating memory */
       str = (char *) realloc(str, 25);
       strcat(str, ".com");
       printf("String = %s,  Address = %u\n", str, str);
    
       free(str);
    
       return(0);
    }
    

    【讨论】:

    • 我想你可以详细说明一下。
    • 答案中添加的示例
    猜你喜欢
    • 2011-04-02
    • 1970-01-01
    • 1970-01-01
    • 2020-12-31
    • 1970-01-01
    • 2014-09-10
    • 1970-01-01
    • 2011-05-23
    • 1970-01-01
    相关资源
    最近更新 更多