0

这是我在 atmel 6 中使用 c 的代码:

#include <avr/io.h>
#include <stdio.h>
#include <math.h>
int a[][][] initialize_hueristic(int[]);



int main(void)
{
    int goal[3],grid_size[3];
    int i, j, k;
    int hueristic[grid_size[0]][grid_size[1]][grid_size[2]];

    hueristic = initialize_hueristic(grid_size);
    hueristic[0][1][0] = 10;
    PORTA = hueristic[0][1][0];






}


int a[][][] initialize_hueristic(int grid_size[])
{
    int hueristic[grid_size[0]][grid_size[1]][grid_size[2]];
    int i, j, k;
    for(i = 0; i < grid_size[0] ; i++)
    {
        for(j = 0; j < grid_size[1]; j++)
            {
                    for(k = 0; grid_size[2]; k++)
                    {
                            hueristic[i][j][k] = 0;
                    }
            }
    }

    return hueristic;
}

atmel 工作室告诉我以下错误:

1.incompatible types when assigning to type 'int[(unsigned int)(grid_size[0])][(unsigned int)(grid_size[1])][(unsigned int)(grid_size[2])]' from type 'int'

2.expected '=', ',', ';', 'asm' or '__attribute__' before 'initialize_hueristic'

3.expected '=', ',', ';', 'asm' or '__attribute__' before 'initialize_hueristic'

有人可以告诉我代码中的错误吗?

4

3 回答 3

0

不平凡的错误(编号 1)与以下行有关:

hueristic = initialize_hueristic(grid_size);

这一行概括了您对 C 中如何管理数组的误解。

您不能分配整个数组,也不能将它们传递给函数或从函数返回它们。您必须逐个元素地复制数组,或者(最好)将指针传递到数组的开头。

您不需要动态分配数组(嵌入式上下文中的动态分配并不常见);但是,您确实希望将hueristic(作为指针)传递给操作它的每个函数。

void initialize_hueristic(int hueristic[][A][B], int grid_size[])
{
    int i, j, k;
    for(i = 0; i < grid_size[0] ; i++) {
        for(j = 0; j < grid_size[1]; j++) {
            for(k = 0; grid_size[2]; k++) {
                hueristic[i][j][k] = 0;
            }
        }
    }
}

您需要在编译时定义值[A][B](或适合这些维度的任何名称);内部数组尺寸必须在编译时固定才能使用[]符号(这也将消除您的其他两个错误)。

然后你可以这样称呼它:

initialize_hueristic(hueristic, grid_size);

您可能会认为该grid_size数组没有意义(假设维度在编译时是固定的)并选择对这些维度使用一些常量。

我还建议检查启发式的拼写(我认为这是您打算使用的词)。

于 2013-02-05T04:53:05.597 回答
0

You are trying to cheat with dynamic memory. You need to be passing a pointer to your heuristic and using malloc. More like this:

void initialize_hueristic(int grid_size[], int ***hueristic)
{
    int i, j, k;
    hueristic = (int*)malloc(grid_size[0])
    for (the inner variable)
        malloc the internal memory
        //etc


for(i = 0; i < grid_size[0] ; i++)
{
    for(j = 0; j < grid_size[1]; j++)
        {
                for(k = 0; grid_size[2]; k++)
                {
                        hueristic[i][j][k] = 0;
                }
        }
}

return hueristic;
}

This will create memory that will exist outside this function. Look up dynamic memory and malloc for more help.

于 2013-02-05T04:40:30.880 回答
0

您的代码中有多个错误。首先当然是函数的返回类型。如果你有一个多维数组,只有最外面的维度可以不指定,所有其他维度都必须指定。

另一个错误是编译器不会捕获的,但会在运行程序时导致奇怪的行为。就是该函数返回一个指向局部变量的“指针”。变量使用的内存hueristic在函数栈上,一旦函数返回就不能使用了。

这两个问题的解决方案是在堆中动态分配内存,并返回该指针。您当然必须记住在完成后释放分配的内存。

于 2013-02-05T04:38:31.320 回答