C语言中的malloc函数是什么意思?


malloc()函数代表内存分配,它动态分配内存块。

它为指定大小保留内存空间并返回一个空指针,指向该内存位置。

malloc()函数附带垃圾值。返回的指针的类型为void。

malloc()函数的语法如下−

ptr = (castType*) malloc(size);

示例

以下示例显示了malloc()函数的用法。

 在线演示

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main(){
   char *MemoryAlloc;
   /* memory allocated dynamically */
   MemoryAlloc = malloc( 15 * sizeof(char) );
   if(MemoryAlloc== NULL ){
      printf("Couldn't able to allocate requested memory
");    }else{       strcpy( MemoryAlloc,"TutorialsPoint");    }    printf("Dynamically allocated memory content : %s
", MemoryAlloc);    free(MemoryAlloc); }

输出

当执行上述程序时,它产生以下结果−

Dynamically allocated memory content: TutorialsPoint

更新于: 2021年2月20日

7K+ 浏览

开始你的事业

通过完成课程获得认证

开始
广告
© . All rights reserved.