How can I allocate memory for array inside a function

前端 未结 4 1610
逝去的感伤
逝去的感伤 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:13

    int *pp;
    p = (int *)malloc(num*sizeof(int));
    if (!pp) /* pp is used uninitialized at this point */
    

    int *p;
    int num, i;
    puts("Enter num of grades:");
    scanf("%d", &num);
    Init(&p, num);
    free(p); /* p is used uninitialized at this point */
    

    If you want to allocate space for a pointer to int inside another function, you need to pass a pointer to pointer:

    ...
    Init(&p, num);
    ...
    int Init(int **pp, int num)
    {
        *pp = malloc(num * sizeof(int));
        ...
    

提交回复
热议问题