为多级指针分配内存

来源:互联网 发布:浙江省网络选修课程 编辑:程序博客网 时间:2024/04/27 17:19


如何理解多级指针

1.       当指针做函数参数的时候,要站在编译器的角度去理解,他只不过是4个字节的变量。

2.       当我们使用指针所指向的内存空间的时候,我们才去关注char * /char ********是二维的,还是八维的。指针变量和它所指向的内存空间变量是两个不同的概念。

 

为一级指针分配内存

方法1:由返回值传回分配的地址

看例程

char *GetCharMem(unsigned int n){    char *s;    s = (char *)malloc(sizeof(char)*n);    return s;} int main(){    char *s = NULL;     s = GetCharMem(sizeof(char)*5);    *s = 'a';    printf("%c\n",*s);    free(s);    s = NULL;     getchar();    return 0;}

 

上面的函数只能为char *分配内存,可以将其改成为各种类型的指针分配内存,如下所示。

void *GetMem(unsigned int n){    void *s;    s = (void *)malloc(n);    return s;} int main(){    char *s = NULL;    int *p1 = NULL;    float *p2 = NULL;     s = (char *)GetMem(sizeof(char));    p1 = (int *)GetMem(sizeof(int));    p2 = (float *)GetMem(sizeof(float));    *s = 'b';    *p1 = 3;    *p2 = 4;    printf("%c\n",*s);    printf("%d\n",*p1);    printf("%f\n",*p2);    free(s);    s = NULL;    free(p1);    p1 = NULL;    free(p2);    p2 = NULL;     getchar();    return 0;}

其实上面的函数GetCharMem()和GetMem()相当于是为malloc()换了一层躯壳,并没有多大意义。

 

方法2:通过二级指针做形参间接分配内存

看例程

int GetCharMem(char **p, unsigned int n){    if(p == NULL || n == 0)    {       return -1;    }    *p = (char *)malloc(sizeof(char)*n);    if(*p == NULL)    {       return -2;    }    return 0;} int main(){int rv = 0;    char *s = NULL;    rv = GetCharMem(&s,5);    if(rv != 0)    {       //各种操作    }    *s = 'a';    printf("%c\n",*s);    free(s);    s = NULL;     return 0;}

 

上面的函数只能为char *分配内存,可以将其改成为各种类型的指针分配内存,如下所示。

int GetMem(void **p, unsigned int n){    if(p == NULL || n == 0)    {       return -1;    }    *p = (void *)malloc(n);    if(*p == NULL)    {       return -2;    }    return 0;} int main(){    char *s = NULL;    int *p1 = NULL;    float *p2 = NULL;     GetMem(&s, sizeof(char)*5);    GetMem(&p1, sizeof(int)*5);    GetMem(&p2, sizeof(float)*5);    *s = 'c';    *p1 = 11;    *p2 = 12;    printf("%c\n",*s);    printf("%d\n",*p1);    printf("%f\n",*p2);    free(s);    s = NULL;    free(p1);    p1 = NULL;    free(p2);    p2 = NULL;     return 0;}

 

为多级指针分配内存

关于为二级指针分配内存在“二级指针的第三种内存模型/二级指针第三种内存模型的一般应用步骤”中也有所提及,不过那种方法是由返回值传回分配的地址,也可以通过三级指针做形参间接分配内存。原理都与一级指针类似,这里就不多说了。

 

0 0
原创粉丝点击