【问题标题】:how to expand an array based on user input in c如何根据c中的用户输入扩展数组
【发布时间】:2021-10-14 02:30:21
【问题描述】:

我正在尝试编写一个程序,询问用户数组的大小,如果再次询问他们,那么数组的大小将根据他们输入的数字而增加。

int main()
{
   int size;
   int n;
   printf("Size of array: ");
   scanf("%d", &n);
   int *ptr = (int*)malloc(n*sizeof(int));
   size = n;
   int n1;  
   do {
       printf("Input the increase size of the array: ");
       scanf("%d", &n1);
       size += n1;
       int *ptr = realloc((size)*sizeof(int));
   } while (n1 != -1);

  return 0;
}


这是我得到的,但我怎样才能把它变成一个函数

【问题讨论】:

    标签: c dynamic-memory-allocation realloc function-definition


    【解决方案1】:
    • 您必须包含相应的头文件才能使用标准库。
    • 您必须将旧指针传递给重新分配给realloc()。
    • 您必须为指针变量指定另一个名称以获得realloc() 的返回值,而不是隐藏(隐藏)变量以存储指向数组的指针。
    • 您应该检查malloc() 和realloc()(和scanf() 的返回值以检查它们是否成功。
    • malloc() 家族的投射结果是considered as a bad practice。

    固定代码:

    #include <stdio.h>
    #include <stdlib.h>
    
    int main(void)
    {
       int size;
       int n;
       printf("Size of array: ");
       if (scanf("%d", &n) != 1) return 1;
       int *ptr = malloc(n*sizeof(int));
       if (ptr == NULL) return 1;
       size = n;
       int n1;  
       do {
           printf("Input the increase size of the array: ");
           if (scanf("%d", &n1) != 1) return 1;
           size += n1;
           int *new_ptr = realloc(ptr, (size)*sizeof(int));
           if (new_ptr == NULL) return 1;
           ptr = new_ptr;
       } while (n1 != -1);
    
      return 0;
    }
    

    【讨论】:

      【解决方案2】:

      首先调用函数 realloc

      int *ptr = realloc((size)*sizeof(int));
      

      不正确。该函数需要两个参数。

      如果你想编写一个改变动态分配数组大小的函数,那么它可以如下所示

      int resize( int **a, size_t n )
      {
          int *tmp = realloc( *a, n * sizeof( int ) );
      
          if ( tmp != NULL ) *a = tmp;
      
          return tmp != NULL;
      } 
      

      并且可以调用该函数,例如

      do {
          n1 = -1;
          printf("Input the increase size of the array: ");
          scanf("%d", &n1);
      } while ( n1 != -1 && resize( &ptr, size += n1 ) );
      
          
      

      【讨论】:

      • 在输入-1 时不使用size - 1 和realloc。
      【解决方案3】:
      if ( scanf( "%d", &n1 ) == 1 )
      {
        int *tmp = realloc( ptr, (size + n1) * sizeof *ptr );
        if ( tmp )
        {
          ptr = tmp;
          size += n1;
        }
      }
      

      如果realloc 不能满足请求,它将返回NULL 并保留原始缓冲区;如果将结果分配回ptr,则可能会丢失对该内存的唯一引用。因此最好将结果分配给一个临时指针值,并在更新ptr之前确保它不是NULL。

      此外,在您知道realloc 成功之前,您不希望更新您的尺寸。

      将其放入函数中:

      bool resize( int **ptr, int *size )
      {
        int n1;
        bool success = false;
      
        printf( "Increase the size by: " );
        if ( scanf( "%d", &n1 ) == 1 )
        {
          int *tmp = realloc( *ptr, (*size + n1) * sizeof **ptr );
          if ( tmp )
          {
            *ptr = tmp;
            *size += n1;
            success = true;
          }
          else
          {
            fputs( "realloc could not extend the buffer\n", stderr );
          }
        }
        else
        {
          fputs( "Error or bad value on input\n", stderr );
        }
        return success;
      }
      

      你会这样称呼它

      int main( void )
      {
        int size = 0;
        int *ptr = NULL;
        ...
        if ( resize( &ptr, &size ) )
          // do stuff with ptr
        else
          // handle resize error
      

      【讨论】:

        【解决方案4】:

        如果你只是想将内存分配移动到一个函数中,你可以这样做:

        int *allocate_array(int *ptr,size_t siz)
        {
            return realloc(ptr,size * sizeof(int));
        }
        
        int main()
        {
            int n, n1, size, *ptr = NULL;
        
            printf("Size of array: ");
            scanf("%d",&n);
            ptr = allocate_array(ptr,n);
            size = n;
            do {
                printf("Input the increase in the array size: ");
                scanf("%d",&n1);
                size += n1;
                ptr = allocate_array(ptr,size);
            } while (n1 > 0);
            return 0;
        }
        

        请注意,您对realloc 的调用不正确,因为第一个参数必须是指向现有数组的指针。此外,您创建了一个新的ptr,其作用域只是 while 循环,然后它不再存在于循环之外。

        【讨论】:

          【解决方案5】:

          您可以使用 realloc 函数重新分配内存。

          void *realloc(void *ptr, size_t size);

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-11-11
            • 2016-02-23
            • 1970-01-01
            • 1970-01-01
            • 2021-09-21
            • 2015-08-14
            相关资源
            最近更新 更多