c - 在函数内分配内存后使用双指针

标签 c pointers

我正在使用 C 中的双指针,想知道是否创建一个初始化表的函数,当我尝试使用 InitStringTable 分配的内存时,它会在返回 main 时崩溃。我相信一个简单的解决方法是使 strTable 成为全局的,然后我相信它可以,但我不想这样做,因为这对我来说更像是一个学习练习,传递表进行修改,即我应该能够从以下位置修改 strTable main 或 InitStringTable 之后的另一个函数修改表。 感谢您提供的任何帮助。

int main()
{
    char** strTable;

    // Allocates memory for string table.
    InitStringTable(strTable);
    // Below lines should be able to copy strings into newly allocated table.
    // Below lines cause crash however.
    strcpy(strTable[0], "abcdef");

    strcpy(strTable[1], "xy");
}

// Allocates memory for the string table. This function should create a table
// of size 10 strings with each string 50 chars long. The code compiles fine.
void InitStringTable(char** table)
{
   int i = 0;

   table = (char**)malloc(sizeof(char)*10);

   for(i = 0; i < 10; i++)
   {
      table[i] = (char*)malloc(sizeof(char)*50);
   }

   for(i = 0; i < 10; i++)
   {
      memset(table[i], 0, 50);
   }

   strcpy(table[0], "string1");
}

最佳答案

C 是按值传递。

分配给table的值在从InitStringTable()返回时丢失。

<小时/>

此外,在分配指向 char 的指针时,请为指向 char 的指针分配空间。

所以这个:

... = (char**)malloc(sizeof(char)*10);

至少应为(假设 C):

... = malloc(sizeof(char*)*10);
<小时/>

一种可能的方法是:

#include <stdlib.h>
#include <string.h>
#include <errno.h>

int InitStringTable(char *** ppptable, const size_t n, const size_t l)
{
   int result = 0;

   if (NULL == ppptable)
   {
     result = -1;
     errno = EINVAL;
   }
   else
   {
     (*ppptable) = malloc(n * sizeof(**ppptable));
     if (NULL == (*ppptable))
     {
       result = -1;
     }
     else
     {
       size_t i = 0;
       for(; i < n; ++i)
       {
         (*ppptable)[i] = calloc(l, sizeof(*(*ppptable)[i]));
         if (NULL == (*ppptable)[i])
         {
           result = -1; 

           /* Failing in the middle requires clean-up. */
           for (; i > 0; --i)
           {
             free((*ppptable)[i-1]);
           }

           free(*ppptable); 
           (*ppptable) = NULL;

           break;
         }
       }
     }
   }

   return result;
 }

这样调用它:

#include <stdlib.h>
#include <stdio.h>

int InitStringTable(char *** ppptable, const size_t n, const size_t l);

int main(void)
{
  int result = EXIT_SUCCESS;
  char ** strTable = NULL;

  if ( -1 == InitStringTable(&strTable, 10, 42)) //* Allocate array with 10 "strings" à 42 chars. */
  {
    perror("InitStringTable() failed");
    result = EXIT_FAILURE;
  }
  else
  {
    strcpy(strTable[0], "abcdef");
    strcpy(strTable[1], "xy");
  }

  return result;
}

不,我不会说“你不想成为三星级程序员!”讨论。

关于c - 在函数内分配内存后使用双指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31221932/

相关文章:

c - 如何在 Linux 上递归列出 C 中的目录?

c - 什么(最小)C 图形库提供这些功能

c - POSIX 中未提及的错误

c - Newlib 在 ARM 嵌入式系统中首次调用时无法分配堆

c - 知道初始地址的指针的地址

c++ - 没有函数指针参数的隐式向上转换?

c - C 错误中的 MPI 操作数

有人可以帮我解决 "unknown type name ' treeElement'"错误吗?

c++ - 类和指针,它们是如何工作的?

c++ - 设置指向静态二维数组的指针