【问题标题】:C Array/Stack/Queue of Arrays?C数组/堆栈/数组队列?
【发布时间】:2020-06-12 09:09:47
【问题描述】:

我是 C 语言的新手,我的任务是创建包含一组元素的东西。我需要有游戏,在这个游戏数组/堆栈/队列中,我应该有一个玩家的移动数组(int 值)。实现这一点的最佳算法可能是什么?以及最简单的方法来检索它们?据我所知,在尝试检索它们时,堆栈会很痛苦。另外,如果您可以帮我为我的数组编写它,因为我还是新手,不知道如何创建队列或其他数组的数组。

到目前为止,这是我的数组:

int array[MAX]; 
insert(array, 1, 12);
insert(array, 2, 13);
insert(array, 3, 14);

// Methods
// Init the array
void init(int *array)
{
    int idx;
    for (idx =0; idx < MAX ; idx++)
    {
        array [idx] = 0;
    }
}

// Insert into the array
void insert ( int *array , int pos , int num)
{
    int idx;

    for ( idx = MAX -1; idx >= pos ; idx --)
    {
        array [idx] = array [idx -1];
    }
    array [idx] = num;
}

【问题讨论】:

  • 这真的取决于如何需要添加/访问/删除您的“集合”移动元素。您的insert() 似乎正在维护一个列表,其中在pos 位置插入了一个新元素,其中pos == 1 是第一个元素(?)——将现有元素pos 向上移动1。

标签: c arrays algorithm stack queue


【解决方案1】:

c中的二维数组,例如10列的表,是: int a[][10]

然后每一行,将相当于:

typedef int row[10]

然后您使用a[x][y] 检索单个单元格。

或者您可以选择创建一个指向 int 的指针数组,例如:

int *array[NUM_ROWS]

然后每一行,将相当于:

typedef int *row

然后你必须 malloc() 为每一行,所需的列数。

【讨论】:

    猜你喜欢
    • 2013-09-30
    • 1970-01-01
    • 2017-06-14
    • 1970-01-01
    • 2010-12-20
    • 2012-11-18
    • 2018-06-06
    • 2020-10-24
    • 2011-11-20
    相关资源
    最近更新 更多