中文字幕一区二区人妻电影,亚洲av无码一区二区乱子伦as ,亚洲精品无码永久在线观看,亚洲成aⅴ人片久青草影院按摩,亚洲黑人巨大videos

C庫中的realloc()函數(shù)及其示例

發(fā)布于:2021-02-05 14:52:20

0

543

0

C realloc() 示例 編程語言

什么是realloc()

realloc()是C庫的功能,用于為已分配的內(nèi)存塊增加更多的內(nèi)存大小。C語言中重新分配的目的是擴(kuò)展當(dāng)前的存儲(chǔ)塊,同時(shí)保留原始內(nèi)容。realloc()函數(shù)有助于通過malloc或calloc函數(shù)減少先前分配的內(nèi)存大小。realloc代表內(nèi)存的重新分配。

在C中realloc的語法:

ptr = realloc (ptr,newsize);

上面的語句在變量newsize中分配具有指定大小的新內(nèi)存空間。執(zhí)行完函數(shù)后,指針將返回到存儲(chǔ)塊的第一個(gè)字節(jié)。新的大小可以大于或小于以前的內(nèi)存。我們不能確定新分配的塊是否將指向與先前存儲(chǔ)塊相同的位置。C語言中的realloc函數(shù)將在新區(qū)域中復(fù)制所有先前的數(shù)據(jù)。它確保數(shù)據(jù)將保持安全。

例如:

#includeint main () {
  char *ptr;
  ptr = (char *) malloc(10);
  strcpy(ptr, "Programming");
  printf(" %s,  Address = %un", ptr, ptr);

  ptr = (char *) realloc(ptr, 20); //ptr is reallocated with new size
  strcat(ptr, " In 'C'");
  printf(" %s,  Address = %un", ptr, ptr);
  free(ptr);
  return 0;
}

如何使用realloc()

下面的C語言程序演示了如何在C語言中使用realloc來重新分配內(nèi)存。

#include <stdio.h>
#include <stdlib.h>
   int main() {
       int i, * ptr, sum = 0;
       ptr = malloc(100);
       if (ptr == NULL) {
           printf("Error! memory not allocated.");
           exit(0);
       }
       
       ptr = realloc(ptr,500);
   if(ptr != NULL)
          printf("Memory created successfullyn");
         
   return 0;

   }

C示例中的realloc結(jié)果:

Memory created successfully

每當(dāng)重新分配導(dǎo)致操作失敗時(shí),它都會(huì)返回空指針,并且先前的數(shù)據(jù)也將被釋放。