c中的指针如何工作

编程入门 行业动态 更新时间:2024-10-26 08:30:14
本文介绍了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函数 msdn.microsoft/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 msdn.microsoft/en-us/library/xbebcx7d.aspx[^] Anyway, it is preferable to know the exact size in advance.

更多推荐

c中的指针如何工作

本文发布于:2023-07-31 15:38:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1259992.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:指针   工作

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!