How can I allocate memory for array inside a function

前端 未结 4 1576
逝去的感伤
逝去的感伤 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 20:09

    First you need to fix the prototype of your function. It should be

    int* Init(int** p, int num);  
    

    Then fix the function definition

    int* Init(int** p, int num)
    {
        //int *pp;   // You don not need this variable
        *p = malloc(num*sizeof(int));   // Allocate memory
        if (!*p)
        {
            printf("Cannot allocate memory\n");
            return NULL; // Return a NULL pointer
        }
    
        return *p;
    }  
    

提交回复
热议问题