(C)将数组与动态内存分配一起使用

tadm123

我想创建一个包含10个元素的简单整数数组。我正在使用动态内存在内存中分配空间,每当我超过该数量时,它将调用realloc以使其大小增加一倍。每当我键入“ q”时,它将退出循环并打印数组。

我知道我的程序中充满了错误,所以请引导我进入错误的地方。

/* Simple example of dynamic memory allocation */

/* When array reaches 10 elements, it calls
   realloc to double the memory space available */

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

#define SIZE_ARRAY 10
int main()
{
    int *a;
    int length=0,i=0,ch;


    a= calloc(SIZE_ARRAY, sizeof(int));
    if(a == NULL)
    {
        printf("Not enough space. Allocation failed.\n");
        exit(0);
    }

    printf("Fill up your array: ");

    while(1)
    {

        scanf("%d",&ch);
        if(ch == 'q')                  //possible mistake here
            break;

        a[length]=ch;
        length++;

        if(length % 10 == 0)   //when length is 10, 20, 30 ..
            {
                printf("Calling realloc to double size.\n");

                a=realloc(a, 2*SIZE_ARRAY*sizeof(int));
            }


    }

    printf("You array is: \n");
    for(;i<length;i++)
        printf("%d ",a[i]);

   return 0;
}

每当我键入“ q”时,程序就会崩溃。我是一个初学者,所以我知道我在犯一个愚蠢的错误。任何帮助将不胜感激。

痴呆症

您不应该将每realloc()一个可能变得非常大,非常快的内存加倍通常,您仅以小块形式扩展内存。realloc()如果旧的内存不能足够长的话,它也有讨厌的习惯来使用内存的另一部分。如果失败,则将旧存储器中的所有数据丢失。通过使用临时指针指向新内存并在成功分配之后交换它们,可以避免这种情况。这只需要额外的指针(最多4个或8个字节)和一个交换(最多只需要几个CPU周期)就可以了。要小心x86,xchg它在多个处理器的情况下会使用锁,这是非常昂贵的!)

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

// would normally be some small power of two, like
// e.g.: 64 or 256
#define REALLOC_GROW 10
int main()
{
  // a needs to be NULL to avoid a first malloc()
  int *a = NULL, *cp;
  // to avoid complications allocated is int instead of size_t
  int allocated = 0, length = 0, i, ch, r;

  printf("Fill up your array: ");
  while (1) {
    // Will also do the first allocation when allocated == length
    if (allocated <= length) {
      // realloc() might choose another chunk of memory, so
      // it is safer to work on copy here, such that nothing is lost
      cp = realloc(a, (allocated + REALLOC_GROW) * sizeof(int));
      if (cp == NULL) {
        fprintf(stderr, "Malloc failed\n");
        // but we can still use the old data
        for (i = 0; i < length; i++) {
          printf("%d ", a[i]);
        }
        // that we still have the old data means that we need to
        // free that memory, too
        free(a);
        exit(EXIT_FAILURE);
      }
      a = cp;
      // don't forget to keep the amount of memory we've just allocated
      allocated += REALLOC_GROW;
    }
    // out, if user typed in anything but an integer
    if ((r = scanf("%d", &ch)) != 1) {
      break;
    }
    a[length] = ch;
    length++;
  }

  printf("Your array is: \n");
  // keep informations together, set i=0 in the loop
  for (i = 0; i < length; i++) {
    printf("%d ", a[i]);
  }
  fputc('\n', stdout);
  // clean up
  free(a);

  exit(EXIT_SUCCESS);
}

如果你玩了一下周围用的启动值allocated,价值REALLOC_GROW和使用乘法,而不是加法的realloc()和更换if(allocated <= length)if(1),你可以触发没有内存不足的错误,看看它是否仍然打印你之前输入的内容。现在,通过a直接使用更改复制时的重新分配,并查看它是否打印数据。情况仍然可能如此,但现在不再保证。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

数组C的动态内存分配

来自分类Dev

使用“ new”的c ++动态内存分配

来自分类Dev

使用动态内存分配将元素添加到数组中

来自分类Dev

在C中的结构内的指针数组的动态内存分配

来自分类Dev

关于C语言数组的动态内存分配

来自分类Dev

指针数组的动态内存分配

来自分类Dev

结构数组的动态内存分配

来自分类Dev

指针数组的动态内存分配

来自分类Dev

结构中数组的动态内存分配

来自分类Dev

如何使用动态内存分配处理C中的矩阵?

来自分类Dev

动态内存分配(C编程)

来自分类Dev

C动态内存分配如何工作

来自分类Dev

C ++动态内存分配奇怪的输出

来自分类Dev

C ++中的动态内存分配

来自分类Dev

C: fork() 动态内存分配

来自分类Dev

使用sbrk的MIPS动态内存分配

来自分类Dev

流行使用动态内存分配

来自分类Dev

在动态内存分配中使用指针

来自分类Dev

使用sbrk的MIPS动态内存分配

来自分类Dev

流行使用动态内存分配

来自分类Dev

C中静态内存分配与动态内存分配的成本

来自分类Dev

c中的动态内存分配,释放使用malloc()之前分配的部分内存

来自分类Dev

取消分配动态内存

来自分类Dev

动态内存分配的限制

来自分类Dev

精确的动态内存分配

来自分类Dev

动态内存分配问题

来自分类Dev

char的动态内存分配**

来自分类Dev

动态内存分配php

来自分类Dev

在C ++中为高维数组分配动态内存的正确方法?