天天看点

c语言malloc(c语言malloc头文件)

p=(PCARDLISTNODE)malloc(sizeof(C?
通过malloc申请sizeof(listnode) 大小的一段连续内存空间,并将该空间地址首地址(指针)强制转换成listnode* 类型,并赋值给lnode变量。这样可以实现动态存储 
访问时 lnode->xx 
不要的时候要释放:free(lnode);
请问今年NOIP的C语言环境是什么?马上就要参加NOIP2009
malloc.h。不过NOIP最好还是静态吧……
谁能解释下malloc在c语言中的用法?
在C语言中使用malloc函数进行动态内存分配。malloc的全称是memory allocation,中文叫动态内存分配。
原型:extern void *malloc(unsigned int num_bytes);
功能:分配长度为num_bytes字节的内存块。注意是分配的内存是按字节来计算的。
返回值:如果分配成功则返回指向被分配内存的指针(此存储区中的初始值不确定),否则返回空指针NULL。当内存不再使用时,应使用free()函数将内存块释放。函数返回的指针一定要适当对齐,使其可以用于任何数据对象。示例如下,注意看注释:
#include
    
//使用malloc需要加stdlib.h的头文件
#include 
    
#include 
    
int main()
//分配内存10个int元素的数组,注意按字节分配,所以要乘以int类型所占的字节
int *p = (int *)malloc(sizeof(int) * 10);
if (p==0) {
printf("不能分配内存\n");
return 0;
//初始化内存
memset(p, 0x00, sizeof(int) * 10);
int inx;
for (inx=0; inx!=10; ++inx) p[inx] = inx;
for (inx=0; inx!=10; ++inx) printf("%d\t", p[inx]);
printf("\n");
free(p);
return ;
}malloc申请的空间是在"堆"上的 
平时我们都是用声明变量来申请空间的,此时申请到的空间是"栈"上的 
栈上的空间, 不需要程序员负责释放. 
例如,在以下函数中 
int go() { 
int a; 
int b[50]; 
在运行到go里面时, 申请了4个字节(int类型是4个字节)的空间来放变量a, 4*50=200个字节的空间来放变量数组b 
在调用go时 
// ... 
go(); 
// ... 
在运行到go()函数的里部,会申请相应的空间,但在退出go()以后,这些空间就会被废弃. 
这在有些时候不能够满足我们的需求,因而就要用到malloc和free 
malloc申请的空间,要由我们程序员来负责释放 
int go() { 
int* a; 
a = malloc(sizeof(int)); 
这样就在堆上申请到了4个字节的空间了(sizeof(int)能够得到int的大小, 返回4). 
我们还可以 
int* a; 
a = malloc(100 * sizeof(int)) 
来申请到100个int的空间. 
退出go以后,空间不会释放.所以要用free来释放.这种问题网路上已经有很多资源可以查了说
C语言中的malloc函数是干什么用的?
动态分配存储空间,动态链表就得用到 
动态内存分配函数链表结构是动态分配存储空间的,即在需要时才开辟一个结点的存储单元,malloc函数就是在内存的动态存储区中分配一个长度为size的连续空间。函数名: malloc 
功 能: 内存分配函数 
用 法: void *malloc(unsigned size); 
程序例: 
#include 
     
    
#include 
     
    
#include 
     
    
#include 
     
    
int main(void) 
char *str; 
/* allocate memory for string */ 
/* This will generate an error when compiling */ 
/* with C++, use the new operator instead. */ 
if ((str = malloc(10)) == NULL) 
{ 
printf("Not enough memory to allocate buffer\n"); 
exit(1); /* terminate program if out of memory */ 
} 
/* copy "Hello" into string */ 
strcpy(str, "Hello"); 
/* display string */ 
printf("String is %s\n", str); 
/* free memory */ 
free(str); 
return 0;      

继续阅读