Search code examples
cpointerspointer-to-pointerpass-by-pointer

End of integer/structure array?


Consider the following functions
void alloco(int **ppa)
{
    int i;
    printf("inside alloco %d\n",ppa); /*this function allocates and fills 20 * sizeof(int) bytes */
    *ppa = (int *)malloc(20 * sizeof(int));
    /*fill all 20 * sizeof(int) bytes */
}

int main()
{
    int *app = NULL;
    int i;
    printf("inside main\n");
    alloco(&app);
    for(i=0;i<20;i++) /*ISSUE::how will i know to traverse only 20 indexes?*/
    printf("app[%d] = %d \n", i, app[i]);
    return(0);
}

Basically how will main() come to know number of bytes to traverse i.e memory allocated by alloco() function. Is there any delimiter like NULL in character arrays?


Solution

  • That is not possible, you need to keep that value somewhere, for example you could do this,

    void alloco(int **ppa, int count)
    {
        int i;
    
        printf("inside alloco %d\n",ppa);
        *ppa = malloc(count * sizeof(int));
        if (*ppa == NULL)
            return;
        for (i = 0 ; i < count ; ++i)
            /* fill it here. */
    }
    
    int main()
    {
        int *app;
        int  i;
        int  count;
    
        count = 20;
        app = NULL;
        printf("Inside main\n");
        alloco(&app, count);
        if (app == NULL)
            return -1;    
        for (i = 0 ; i < count ; i++)
            printf("app[%d] = %d \n", i, app[i]);
        /* done with `app' */
        free(app);
        return 0;
    }
    

    Many other combinations could work, for example

    int alloco(int **ppa)
    {
        int i;
    
        printf("inside alloco %d\n",ppa);
        *ppa = malloc(20 * sizeof(int));
        if (*ppa == NULL)
            return;
        for (i = 0 ; i < count ; ++i)
            /* fill it here. */
        return 20;
    }
    
    int main()
    {
        int *app;
        int  i;
        int  count;
    
        printf("Inside main\n");
    
        app = NULL;
        count = alloco(&app);
        if (app == NULL)
            return -1;    
        for (i = 0 ; i < count ; i++)
            printf("app[%d] = %d \n", i, app[i]);
        /* done with `app' */
        free(app);
        return 0;
    }
    

    But I personally don't like this because if there is going to be a fixed number of integers it's not a good idea to use malloc() just,

    int main()
    {
        int  app[20];
        int  i;
    
        printf("Inside main\n");    
        for (i = 0 ; i < sizeof(app) / sizeof(app[0]) ; i++)
            printf("app[%d] = %d \n", i, app[i]);
        return 0;
    }