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

时间:2022-07-24
本文章向大家介绍c语言二级指针的使用,malloc内存申请,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
#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 memoryn");
        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] = %dn", i, arr[i]);
    }

    //free the memory
    free(arr);


    return 0;

}

输入结果如下: