realloc ()- 更改保留存储块大小

格式

#include <stdlib.h>
void *realloc(void *ptr, size_t size);

语言级别

ANSI

线程安全

描述

realloc() 函数会更改先前保留的存储块的大小。 ptr 自变量指向块的开头。 size 参数给出块的新大小 (以字节为单位)。 块的内容不变,直到新旧尺寸的更短。

如果 ptrNULL,那么 realloc() 将保留 大小 字节的存储器块。 它不一定为每个元素的所有位都提供 0的初始值。

如果 size0 并且 ptr 不是 NULL,那么 realloc() 将释放分配给 ptr 的存储器并返回 NULL

注:
  1. 所有堆存储器都与调用函数的激活组相关联。 因此,应该在同一激活组中分配,取消分配和重新分配存储器。 不能在一个激活组中分配堆存储器,也不能从另一个激活组中取消分配或重新分配该存储器。 有关激活组的更多信息,请参阅 ILE 概念 手册。
  2. 如果已在当前激活组中启用快速池内存管理器,那么将使用快速池内存管理器来检索存储器。 请参阅_C_Quickpool_Init ()-初始化快速池内存管理器 以获取更多信息。

返回值

realloc() 函数返回指向重新分配的存储块的指针。 块的存储位置可由 realloc() 函数移动。 因此, realloc() 函数的 ptr 自变量不一定与返回值相同。

如果 size0,那么 realloc() 函数将返回 NULL。 如果没有足够的存储空间将块扩展到给定大小,那么原始块保持不变,并且 realloc() 函数返回 NULL

返回值所指向的存储器,用于存储任何类型的对象。

要在不更改 C 源代码的情况下使用 太字节空间 存储器而不是单层存储器,请在编译器命令上指定 TERASPACE (*YES *TSIFC) 参数。 这会将 realloc() 库函数映射到 _C_TS_realloc()(其太字节空间存储器对等项)。 每次调用 _C_TS_realloc() 时可分配的最大太字节空间存储量为 2GB -240 或 214743408 字节。 有关太字节空间存储器的其他信息,请参阅 ILE Concepts 手册。

示例

此示例为 array 的提示大小分配存储器,然后使用 realloc() 来重新分配块以保存数组的新大小。 每次分配后都会打印数组的内容。
#include <stdio.h>
#include <stdlib.h>
 
int main(void)
{
  long * array;    /* start of the array */
  long * ptr;      /* pointer to array   */
  int    i;        /* index variable     */
  int  num1, num2; /* number of entries of the array */
  void print_array( long *ptr_array, int size);
  printf( "Enter the size of the array\n" );
  scanf( "%i", &num1);
  /* allocate num1 entries using malloc() */
  if ( (array = (long *) malloc( num1 * sizeof( long ))) != NULL )
  {
     for ( ptr = array, i = 0; i < num1 ; ++i ) /* assign values */
        *ptr++ = i;
     print_array( array, num1 );
     printf("\n");
  }
  else { /*  malloc error  */
    perror( "Out of storage" );
    abort();
  }
  /* Change the size of the array ... */
  printf( "Enter the size of the new array\n" );
  scanf( "%i", &num2);
  if ( (array = (long *) realloc( array, num2* sizeof( long ))) != NULL )
  {
     for ( ptr = array + num1, i = num1; i <= num2; ++i )
        *ptr++ = i + 2000;  /* assign values to new elements */
     print_array( array, num2 );
  }
  else { /* realloc error */
    perror( "Out of storage" );
    abort();
  }
}
 
void print_array( long  * ptr_array, int size )
{
  int i;
  long * index = ptr_array;
  printf("The array of size %d is:\n", size);
  for ( i = 0; i < size; ++i )           /* print the array out    */
    printf( "  array[ %i ] = %li\n", i, ptr_array[i] );
}
 
/**** If the initial value entered is 2 and the second value entered 
      is 4, then the expected output is:
Enter the size of the array
The array of size 2 is:
  array[ 0 ] = 0
  array[ 1 ] = 1
Enter the size of the new array
The array of size 4 is:
  array[ 0 ] = 0
  array[ 1 ] = 1
  array[ 2 ] = 2002
  array[ 3 ] = 2003                                                */

相关信息