Using Double Pointers after memory allocated within function

前端 未结 3 1869
自闭症患者
自闭症患者 2020-11-28 16:41

I was playing with double pointers in C and was wondering if I create a function that initializes the table, it crashes on going back to main when I try to make use of the m

3条回答
  •  无人及你
    2020-11-28 17:41

    C is pass by value.

    The value assigned to table is lost on returning from InitStringTable().


    Also when allocating pointers to char ask for room for pointers to char.

    So this:

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

    shall at least be (assuming C):

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

    A possible approach to this would be:

    #include 
    #include 
    #include 
    
    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;
     }
    

    Call it like this:

    #include 
    #include 
    
    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;
    }
    

    And no, I won't get into this ridiculous "You don't wanna be a 3-star-programmer!" discussion.

提交回复
热议问题