How can I allocate memory for array inside a function

前端 未结 4 1607
逝去的感伤
逝去的感伤 2020-12-21 19:41

I am trying to receive a number from the user. And create an array with that number, but, inside a function. Here are my few attempts, I get into run time errors. Help is ve

4条回答
  •  醉话见心
    2020-12-21 19:59

    You have done well upto the point you understood you need to pass a pointer to pointer. But your function signature doesn't take an int **. Either you pass a pointer to pointer and store the allocated memory in it:

    void Init(int **pp, int num)
    {
        int *p;
        p = malloc(num*sizeof(int));
        if (!p)
        {
            printf("Cannot allocate memory\n");
        }
        *pp = p;
    }
    

    And check if the Init() returns a proper pointer:

       Init(&p, num);
       if(p == NULL) {
          /*Memory allocation failed */
       }
    

    Or allocate memory and return the pointer:

    int* Init(int num)
    {
        int *p;
        p = malloc(num*sizeof(int));
        if (!p)
        {
            printf("Cannot allocate memory\n");
        }
    
        return p;
    }
    

    and from main() call as:

    int * p = Init(num);
    if(p == NULL) {
       /*Memory allocation failed */
    }
    

    Change the prototype of Init() accordingly.

    In any case, you must not free() the pointer in Init(). That just de-allocates memory immediately and you'll be left with a dangling pointer.

    And you need to free() in the main() after you are done with it.

提交回复
热议问题