您可以在C中定义运行时数组的大小

6 c malloc dynamic-memory-allocation

C的新手,非常感谢您的帮助.

是否可以在C中定义数组而无需指定其大小或初始化它.

例如,我可以提示用户输入数字并将它们存储在int数组中吗?我不知道他们预先输入了多少号码.

我现在能想到的唯一方法是定义最大尺寸,这不是一个理想的解决方案......

Bob*_*toe 13

好吧,你可以动态分配大小:

#include <stdio.h>

int main(int argc, char *argv[])
{
  int *array;
  int cnt;
  int i;

  /* In the real world, you should do a lot more error checking than this */
  printf("enter the amount\n");
  scanf("%d", &cnt);

  array = malloc(cnt * sizeof(int));

  /* do stuff with it */
  for(i=0; i < cnt; i++)
    array[i] = 10*i;

  for(i=0; i < cnt; i++)
    printf("array[%d] = %d\n", i, array[i]);

  free(array);

  return 0;
}
Run Code Online (Sandbox Code Playgroud)


Joe*_*oel 6

也许是这样的:

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

/* An arbitrary starting size. 
   Should be close to what you expect to use, but not really that important */
#define INIT_ARRAY_SIZE 8

int array_size = INIT_ARRAY_SIZE;
int array_index = 0;
array = malloc(array_size * sizeof(int));

void array_push(int value) {
  array[array_index] = value;
  array_index++;
  if(array_index >= array_size) {
    array_size *= 2;
    array = realloc(array, array_size * sizeof(int));
  }
}

int main(int argc, char *argv[]) {
  int shouldBreak = 0;
  int val;
  while (!shouldBreak) {
    scanf("%d", &val);
    shouldBreak = (val == 0);
    array_push(val);
  }
}
Run Code Online (Sandbox Code Playgroud)

这将提示您输入数字并将其存储在数组中,如您所要求的那样.在给定0时传递将终止.

您创建了一个array_push用于添加到数组的访问器函数,realloc当您用完空间时,可以使用此函数调用.每次分配的空间量增加一倍.最多你会分配你需要的双倍内存,最坏的情况下你会调用realloclog n次,其中n是最终的数组大小.

您可能还想在调用malloc和realloc后检查是否有失败.我上面没有这样做过.