c中的指针如何工作 [英] Pointers in c how it works

查看:98
本文介绍了c中的指针如何工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,
我怀疑malloc函数将如何为指针分配内存

如果我那样做(以下)

* p = malloc(sizeof(int)* 1024);

它分配一个内存..

但我只在其中使用一些内存..我想删除或释放未使用的内存.

请给我一个建议.

在此先感谢.

解决方案

希望 [ ^ ]可能会为您提供帮助.

在堆上分配内存(例如256个整数):

int size = 256; //<-- Can be whatever you need (doesn''t have to be a hard coded constant, could be some variable that''s evaluated at run time)

//Using malloc/free
int *iArray;
iArray = (int *) malloc(size*sizeof(int));  //Allocate (requires size in bytes, hence the sizeof() call)

//To check if valid and take appropriate action
if(iArray == NULL)
{
  printf("Error: Failed to allocated required memory.");
  exit(1);
}

//... Use
free(iArray);                               //Deallocate when done


您可以为此目的使用realloc函数
http://msdn.microsoft.com/en-us/library/xbebcx7d.aspx [ ^ ]
无论如何,最好事先知道确切的大小.


Hi All,
I have doubt in that how the malloc function will allocate memory for the pointer

if i done like that(following)

*p=malloc(sizeof(int)*1024);

it allocate a memory..

but i use some memory only in that.. i want to delete or free the unused memory .

Please give me a suggestions.

Thanks in Advance.

解决方案

Hope this[^] might help you.


Allocating memory on heap (256 integers in example):

int size = 256; //<-- Can be whatever you need (doesn''t have to be a hard coded constant, could be some variable that''s evaluated at run time)

//Using malloc/free
int *iArray;
iArray = (int *) malloc(size*sizeof(int));  //Allocate (requires size in bytes, hence the sizeof() call)

//To check if valid and take appropriate action
if(iArray == NULL)
{
  printf("Error: Failed to allocated required memory.");
  exit(1);
}

//... Use
free(iArray);                               //Deallocate when done


You can use the realloc function for that purpose
http://msdn.microsoft.com/en-us/library/xbebcx7d.aspx[^]
Anyway, it is preferable to know the exact size in advance.


这篇关于c中的指针如何工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆