Chinaunix首页 | 论坛 | 博客
  • 博客访问: 294212
  • 博文数量: 77
  • 博客积分: 1422
  • 博客等级: 上尉
  • 技术积分: 932
  • 用 户 组: 普通用户
  • 注册时间: 2007-08-21 12:39
文章分类
文章存档

2011年(1)

2009年(3)

2008年(73)

我的朋友

分类:

2008-07-05 12:04:38

指针的指针内存分配理解起来很容易的

例如 PtrType **p ;

1.首先要记住p是个指针,所以要给p一片空间 p = (PtrType **)malloc(num * sizeof(PtrType *)) ;

2.然后,还要切忌*P仍然是指针,所以   *(p+i) = (PtrType *)malloc(num_i * sizeof(PtrType)) ;

3.为了便于推广,不妨把一个*看成一代孩子吧。有多少代人就得分配多少代房子哦,要不没地方住,就是野孩子啦。

4.if (PtrType == char)  记得赋值的时候(*(p+i))[最大标号] = '\0'啊


请看下面一段代码:

#include <stdlib.h>

int main()
{
int blockNumber = 0, blockSize = 0, i;
int **pMems = NULL;

printf("输入要分配的内存块数 : ");
scanf("%d", &blockNumber);
printf("输入分配的内存块大小 : ");
scanf("%d", &blockSize);

if(blockNumber < 1 || blockSize < 1)
{
printf("无效的输入。\n");
getchar();
return 1;
}

printf("\n正在申请动态内存指针内存块...\n");
pMems = (int**)calloc(blockNumber, sizeof(int));
if(pMems == NULL)
{
printf("申请动态内存指针内存块失败。\n");
getchar();
return 2;
}

printf("\n正在申请 %d 块内存,...\n", blockNumber);
for(i=0; i< blockNumber; i++)
{
*pMems = (int*)malloc(blockSize);
if(*pMems == NULL)
{
printf("申请第 %d 块内存失败。\n", i + 1);
getchar();
return 3;
}
pMems++;
}
pMems -= blockNumber;

printf("成功!\n");
printf("Power by Zealic");
getchar();
return 0;
}


原文地址 http://hi.baidu.com/l1uyan/blog/item/b49eee25e97cd86334a80fd5.html


下面是我的代码:

#include <stdlib.h>

int main(void)
{
    int blockNumber = 0;
    int blockSize = 0;
    int i;
    int **pMems = NULL;

    printf("Please input the number of block you want to allocate\n");
    scanf("%d", &blockNumber);
    printf("Please input the size of each block you want to allocate\n");
    scanf("%d", &blockSize);

    if (blockNumber < 1 || blockSize < 1)
    {
        printf("invalid input\n");
        getchar();
        return -1;
    }

    printf("\nrequesting for memory block for dynamic memroy pointer...\n");
    pMems = (int **)calloc(blockNumber, sizeof(int *));
    if (pMems == NULL)
    {
        printf("requesting for memory block for dynamic memory pointer failed.\n");
        getchar();
        return -1;
    }

    printf("requesting for %d blocks memories...\n", blockNumber);
    for (i = 0; i < blockNumber; i++)
    {
        printf("requesting for %dth block memory...\n", i + 1);
        if ((*(pMems + i) = (int *)malloc(blockSize)) == NULL)
        {
            printf("requesting for %dth block memory failed\n", i + 1);
            getchar();
            return -1;
        }
    }
    
    printf("successfully\n");
    getchar();

    printf("releasing %d blocks memories...\n", blockNumber);
    for (i = 0; i < blockNumber; i++)
    {
        printf("releasing %dth block memory...\n", i + 1);
        free(*(pMems + i));
    }

    printf("\nreleasing memory block for dynamic memroy pointer...\n");
    free(pMems);

    pMems = NULL;

    return 0;
}
        

阅读(1235) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~