c语言二级指针的使用,malloc内存申请

时间:2024-03-04 11:42:45
#include<stdio.h>
#include<stdlib.h>


void AllocateMemory(int **pGetMemory, int n)
{

    int *p = (int*)malloc(sizeof(int) * n);

    if (p == NULL)
    {
        *pGetMemory = NULL;
    }
    else
    {
        *pGetMemory = p;
    }
}


int main()
{
    int *arr = NULL;
    int len = 10;
    int i = 0;

    //Allocate the memory
    AllocateMemory(&arr, len);

    if (arr == NULL)
    {
        printf("Failed to allocate the memory\n");
        return -1;
    }

    //Store the value
    for (i = 0; i < len; i++)
    {
        arr[i] = i;
    }

    //print the value
    for (i = 0; i < len; i++)
    {
        printf("arr[%d] = %d\n", i, arr[i]);
    }

    //free the memory
    free(arr);


    return 0;

}

输入结果如下: