多维数组

时间:2016-04-30 17:44:41

标签: c

我对C中的多维数组有困难。
我们必须创建一个多维数组,用户必须在其中输入数组的大小。之后根据大小C来创建一个多维数组。请记住,在中心总是必须有' 在一方的每一边都应该有' 2'。在' 2'的每一边应该有' 3',取决于数组的大小。也显示在图像中。  可以找到数组的中点,但是当我这样做时:int Array[size/2][size/2]它给了我错误。以及我如何调整其他2,3和其他数字?

这是我现在编写的代码:

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

int main(){
 const size;
 printf("Enter the size: ");
 scanf("%d", &size);
 int Grid[size][size];
 Grid[size/2][size/2] = 1;
 printf("%d", Grid[1][1]);
 return 0;
}

enter image description here

3 个答案:

答案 0 :(得分:1)

首先,你不应该在C中做这样的事情:

int grid[size][size];

如果您对了解原因感兴趣,请查看 C11的初始化段落:

  

初始化程序不应尝试为未初始化的实体中包含的对象提供值。

     

要初始化的实体的类型应为未知大小的数组或不是可变长度数组类型的完整对象类型。

然后,我不是

的粉丝
 const size;

由于类型不明确且您的变量不是常量。即使您正在使用scanf也会在功能期间修改 size的值。

但是,接下来,让我们解决问题;)

我建议你使用一个函数来分配你的数组。它将有助于澄清您的代码:

int**   create_array(int    size)
{
  int   i;
  int** array;

  i = 0;
  // You allocate the first dimension of your array
  // (the one that will contain other arrays)
  array = malloc(size * sizeof(int *));
  if (array != NULL)
    {
      while (i < size)
        {
          // You allocate each 'sub-array' that will contain... ints !
          array[i] = malloc(size * sizeof(int));
          i += 1;
        }
    }
   return (array);
}

现在这个函数返回一个分配好的数组,你想要的大小。不要忘记检查你的呼叫功能中是否NULL,并将其释放(如果已分配)。

要释放数组,我会让你自己编写函数,因为它与初始化非常相似。但是,要小心,考虑一些子数组可能是NULL

然后初始化。我能想到的最简单的方法是迭代你的数组并从中心计算增量。

int most_far;

////
/// Insert the loop stuff here...
//
if (x == size/2 && y == size/2)
  array[x][y] = 1;
else
  {
    // You could use a ternary here but I don't know if you're familiar with them
    // You're getting the position that is the most far from center...
    if (abs(x - size/2) > abs(y - size/2))
       most_far = abs(x - size/2);
    else
       most_far = abs(y - size/2);
    // With this position, you calculate the 'distance' between the center and your position.
    // This distance is your number ! :D
    array[x][y] = most_far;
  }
 //
 /// End of the loop, interations, etc...
 ////

小提示:我建议你在一些返回布尔值的函数中进行填充。如果在填充期间找到一个子数组NULL,则此布尔值将为false。如果是这样,您可能不想阅读/显示它!

Pfiouh,我写的是一个巨大的答案! 希望它不会吓到你(并且你会在其中找到一些帮助)

答案 1 :(得分:0)

如果您的目标元素位于a[2][2]位置,那么条件将是这样的。 将i视为行,j为列。

 if(a[i+1][j]==a[i+1][j+1]==a[i+1][j-1]==a[i][j+1]==a[i][j-1]==a[i-1][j]==a[i-1][j+1]==a[i-1][j-1])
       flag=1;   \\any process you want

并且您只能在声明时将常量指定给数组。您无法分配类似

的值
int array[size/2][size/2];

答案 2 :(得分:0)

您可以考虑以下两种方法:

  1. 在不断增长的广场上填写条目。 (即填写所有1,然后是2s,然后是3s,......)
  2. 找出&#34;公式&#34;或每行的程序。
  3. 看第一种方法:

    void fillSquare(int **arr, int n, int size)
    {
        fillSquareTopSide(arr, n, size);
        fillSquareLeftSide(arr, n, size);
        fillSquareRightSide(arr, n, size);
        fillSquareBottomSide(arr, n, size);
    }
    

    其中n是当前号码(123),大小为3。然后是fillSquareTopSide

    的可能实现
    void fillSquareTopSide(int **arr, int n, int size)
    {
        for(int i = size - n; i < size + n; i++)
            arr[size - n][i] = n;
    }