C malloc()

malloc() 函数在 stdlib.h 头文件中定义。它有助于分配指定的内存并返回指向它的指针。malloc() 函数不能将已分配的内存设置为零。


void *malloc(size_t size); #where sizes hould be in bytes

 

malloc() 参数: 

malloc() 函数接受两个参数。此函数有助于动态分配内存块。我们可以将 malloc 函数分配给任何指针。

参数 描述 必需/可选
size 这是内存块的大小,以字节为单位 必需

malloc() 返回值

malloc() 函数的返回值为指向已分配内存的指针。

输入 返回值
成功 内存指针
失败 NULL

malloc() 示例 

示例 1:C 语言中 malloc() 函数的工作原理?


#include <stdio.h>
#include <stdlib.h>

int main()
{
   char *s;

   /*memory allocation */
   s = (char *) malloc(12);
   strcpy(s, "programming");
   printf("String = %s,  Address = %u\n", s, s);

   /* Reallocating memory */
   s = (char *) realloc(s, 20);
   strcat(s, ".com");
   printf("String = %s,  Address = %u\n", s, s);

   free(s);
   
   return(0);
}

输出


String = programming, Address = 355090448
String = programming.com, Address = 355090448

示例 2:C 语言中 malloc() 的工作原理?


#include <stdio.h>
#include <stdlib.h>

int main (){
  int *p;
  p = malloc(15 * sizeof(*p)); 
    if (p != NULL) {
      *(p + 5) = 480; 
      printf("6th integer value is %d",*(p + 5));
    }
}

输出


6th integer value is 480