c - 二级指针的一个疑问
本文介绍了c - 二级指针的一个疑问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
问题的产生
要实现一个函数,函数内部 malloc申请一块内存,然后针对这块内存做一系列操作,操作这部分忽略不计,不是探讨的问题,我们要返回申请的这片内存的地址.
#include <stdio.h>
#include <stdlib.h>
/*获取malloc内存的地址*/
int getaddress(int **address)
{
int * tmp = NULL;
int size = 64;
tmp = malloc(size *sizeof(int));
*address = tmp;
printf("Address of malloc memory is:%p\n",tmp);
return 0;
}
int main()
{
int *pointer = NULL;
getaddress(&pointer);
printf("Address of pointer is:%p\n",pointer);
return 0;
}
输出结果终于符合我们预期:
Address of malloc memory is:0x100202350
Address of pointer is:0x100202350
Program ended with exit code: 0
pointer的值就是我们在函数中所申请的内存地址.
写道这里我有疑问,函数getaddress中是否真正需要tmp中间变量呢?
/*
Name: 二级指针
Copyright: segment
Author: 风清扬
Date: 13/06/17 22:15
Description: pointer
*/
#include <stdio.h>
#include <stdlib.h>
/*获取malloc内存的地址*/
int getaddress(int **address)
{
int size = 64;
*address = malloc(size *sizeof(int));
printf("Address of malloc memory is:%p\n",address);
return 0;
}
int main()
{
int *pointer = NULL;
getaddress(&pointer);
printf("Address of pointer is:%p\n",pointer);
return 0;
}
运行结果居然是:
Address of malloc memory is:0x7fff5fbff7b0
Address of pointer is:0x100300000
Program ended with exit code: 0
那么为什么会是这样呢?
tmp只是中间变量,我现在去掉了中间变量,仅此而已.
解决方案
去掉中间变量是没有问题的,但是,getaddress函数里面应该是printf("Address of malloc memory is:%p\n",*address);
才对。address
前面有个*
。
另外多说两句,比较推荐的写法是:
#include <stdio.h>
#include <stdlib.h>
/*获取malloc内存的地址*/
int* getaddress()
{
int * tmp = NULL
int size = 64;
tmp = malloc(size *sizeof(int));
printf("Address of malloc memory is:%p\n",tmp);
return tmp;
}
int main()
{
int *pointer = NULL;
pointer = getaddress();
printf("Address of pointer is:%p\n",pointer);
return 0;
}
这篇关于c - 二级指针的一个疑问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文