Using Double Pointers after memory allocated within function

前端 未结 3 1866
自闭症患者
自闭症患者 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:19

    The lines below InitStringTable() crash, because they are trying to perform operations on a memory address that is neither in the same scope as theirs nor have any reference to
    that memory address.

    The function InitStringTable() allocates memory to the table, but cannot be accessed by the
    calling function (here main), because the memory is local to the function in which it
    allocated.
    Therefore in order to use the same memory address for operations in the
    calling function you must pass a reference of that address to the calling function.

    In your program you can do it as under :
    Declare the function as :-

    char **InitStringTable(char **);
    
    
    int main()
    {
        char** strTable;
        strTable = InitStringTable(strTable);   
        strcpy(strTable[0], "abcdef");   
        strcpy(strTable[1], "xy");
    }   
    
    char **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");
    
    
       /* after the function has finished its job, return the address of the table */    
       return table;
    }
    

提交回复
热议问题