动态内存malloc,calloc,relloc,memset

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
   int* p =(int *)malloc (sizeof(int)*3);
   for (int i = 0; i < 3; i++)printf("%d ",p[i]);printf("\n");
   /*
    The  malloc()  function  allocates size bytes and returns a pointer to the allo‐
    cated memory.  The memory is not initialized.   If  size  is  0,  then  malloc()
    returns  either  NULL,  or a unique pointer value that can later be successfully
    passed to free().
    */
   memset(p,0,sizeof(sizeof(int)*3));
   for (int i = 0; i < 3; i++)printf("%d ",p[i]);printf("\n");
   free(p);
    //The void *memset(void *s, int c, size_t n); function fills the first n bytes of the memory 
    //area pointed to by s with the constant byte c.

   int* a = (int*)calloc(5,sizeof(int));
   for (int i = 0; i < 5; i++){printf("%d ",a[i]);a[i]=i;};printf("\n");
   /*
    The  calloc()  function  allocates memory for an array of nmemb elements of size
    bytes each and returns a pointer to the allocated memory.  The memory is set  to
    zero.   If  nmemb  or  size is 0, then calloc() returns either NULL, or a unique
    pointer value that can later be successfully passed to free().
    */

   int* b = (int*)realloc(a,7*sizeof(int));
   for (int i = 0; i < 7; i++)printf("%d ",b[i]);printf("\n");
    /*
    The realloc() function changes the size of the memory block pointed to by ptr to
    size  bytes.   The contents will be unchanged in the range from the start of the
    region up to the minimum of the old and new sizes.  If the new  size  is  larger
    than  the  old  size, the added memory will not be initialized.  If ptr is NULL,
    then the call is equivalent to malloc(size), for all values of size; if size  is
    equal  to  zero,  and ptr is not NULL, then the call is equivalent to free(ptr).
    Unless ptr is NULL, it must have been returned by an earlier call  to  malloc(),
    calloc(), or realloc().  If the area pointed to was moved, a free(ptr) is done.
   */
   memset(a,0xFF,sizeof(int)*7);
   for (int i = 0; i < 7; i++)printf("%d ",b[i]);printf("\n");
   free(b);

   return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值