【问题标题】:What is the best way to store N amount arrays ? C [closed]存储 N 个数组的最佳方法是什么? C [关闭]
【发布时间】:2017-08-03 19:53:43
【问题描述】:

我的输入应该是这样的:

n array1 array2 array3 array4 ... arrayn

其中 n 是一个整数,array1 .. arrayn 是数组。数组总是有 4 个元素。 我可以这样做:

int n,array[100][4];
for(int i=0;i<=n-1;i++)
{   
    for(int j=0;j<=3;j++)
    {
        scanf("%d",&array[i][j]);
    }

}

但这是一个矩阵,我认为有更好的解决方案,但我真的想不出...

【问题讨论】:

  • 矩阵有什么问题?
  • 旁注:你不想scanf("%d",&amp;array[i][j]);吗?
  • @Barmar 我需要学习尽可能多地节省空间/内存......我只是在寻找其他替代方案,我的大脑拒绝想出不同的东西。
  • @CraigEstey 是的,对不起,谢谢,我会编辑它
  • VLA 是否有帮助:(例如)int n = 100; int array[n][4];?或者,如果n 对堆栈来说太大,则执行int *array = malloc(n * 4 * sizeof(int));,然后手动执行您自己的二维索引(例如)#define ARRAY(y,x) array[((y) * 4) + (x)],然后使用ARRAY(i,j)

标签: c arrays matrix


【解决方案1】:

存储 N 个数组的最佳方法是什么?
数组总是有 4 个元素

一些选择:什么是最好的取决于未说明的编码目标。如果不确定,请考虑选项B。每个都使用大约相同数量的内存。 VLA 位于本地,应避免使用大型 n

  unsigned n = rand();

  // arrayA as array n of array 4 of int
  // Variable-Length-Array (VLA) available in C99 and optionally in C11
  // UB if n == 0
  int arrayA[n][4];
  arrayA[0][0] = 42;
  // no free() needed.  Become invalid at the end of the block

  // arrayB as pointer to array 4 of int
  // Allocate memory for a n 1D arrays
  int (*arrayB)[4] = malloc(sizeof *arrayB * n);
  if (n > 0) arrayB[0][0] = 42; 
  free(arrayB);  // Valid until free'd

  // arrayC as pointer to array n of array 4 of int
  // Allocate memory for a 2D VLA  (C99,C11 maybe)
  // UB if n == 0
  int (*arrayC)[n][4] = malloc(sizeof *arrayC);
  (*arrayC)[0][0] = 42;
  free(arrayC); // Valid until free'd

malloc() 的返回值应检查 NULL-ness

  p = malloc(sizeof *p * n);
  if (p == NULL && n > 0) {
    Handle_OutOfMemory();
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-03
    • 2021-05-06
    • 2021-12-05
    • 1970-01-01
    • 2013-02-15
    • 2011-11-01
    • 2020-09-09
    相关资源
    最近更新 更多