Chinaunix首页 | 论坛 | 博客
  • 博客访问: 982506
  • 博文数量: 327
  • 博客积分: 9995
  • 博客等级: 中将
  • 技术积分: 4319
  • 用 户 组: 普通用户
  • 注册时间: 2009-05-25 11:21
文章存档

2011年(31)

2010年(139)

2009年(157)

我的朋友

分类: C/C++

2009-12-06 17:56:57

#include <stdio.h>
#include <stdlib.h>
/*Three methods to return the memory area allocated by malloc*/

/* 第一种方法:返回锁分配内存的首地址,将首地址强制转换为int或long保存
  在以后调用中,将该数值请转换为所需类型对应的指针类型*/


int alloc_mem_1(int num)
{
    int *q;

    q = (int *) malloc(num);
    return (int) q;
}

/*第二种方法:
类似于第一种方法,只是将内存首地址转换为int或long保存在指针中。
以后调用传递变量时,可以将一个int或long变量取址传递即可*/


void alloc_mem_2(int *p, int num)
{
    int *q;

    q = (int *) malloc(num);
    *p = (int) q;
}

/* 第三种方法:
   使用指向指针的指针保存分配存储内存的首地址
*/

void alloc_mem_3(int **p, int num)
{
    *p = (int *) malloc(num);
}

int main(void)
{
    int i;
    int handle;

    /*three pointers to test three methods*/
    int *p1 = NULL;
    int *p2 = NULL;
    int *p3 = NULL;

    /*test of alloc_mem_1()*/
    printf("1: test of alloc_mem_1()\n");
    handle = alloc_mem_1(10 * sizeof(int));
    p1 = (int *)handle;
    for (i = 0; i < 10; i++){
        *(p1 + i) = i ;
        printf("%d\t", p1[i]);
    }

    printf("\n");
    free(p1);

    /*test of alloc_mem_2()*/
    printf("2: test of alloc_mem_2()\n");
    alloc_mem_2(&handle, 10 * sizeof(int));
    p2 = (int *)handle;
    for (i = 0; i < 10; i++){
        p2[i] = i * 2;
        printf("%d\t", p2[i]);
    }

    printf("\n");
    free(p2);

    /*test of alloc_mem_3()*/
    printf("3: test of alloc_mem_3()\n");
    alloc_mem_3(&p3, 10 * sizeof(int));
    for (i = 0; i < 10; i++){
        p3[i] = i * 3;
        printf("%d\t", p3[i]);
    }

    printf("\n");
    free(p3);

    return 0;
}


其中:
1.第一种方法是采用返回值的方式,将所分配的内存的首地址以整型之返回。在调用该函数是,将其返回值强制转换为相应类型的指针即可,我这里转换为整形指针。然后就可以以该内存为首地址,进行读写num个整形数据;
2.第二种方法的实现类似于第一种,只是将所分配内存的首地址存在一个整形指针里面;
3.第三种方法应该是使用指向指针的指针来实现动态内存的传递。这个方法在《高质量C/C++编程》中最后的一份试题中提到了这种方法。

以上三种方法中,第三种方法应该是常用的,也是容易理解的。前两种方法的实现体现在一些特别的方面,譬如,GUI编程中窗口的handle的使用,等等。

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