Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/62.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 数组类型“Ship[10]”不可赋值-在使用结构和数组时_Arrays_C_Pointers_Struct - Fatal编程技术网

Arrays 数组类型“Ship[10]”不可赋值-在使用结构和数组时

Arrays 数组类型“Ship[10]”不可赋值-在使用结构和数组时,arrays,c,pointers,struct,Arrays,C,Pointers,Struct,我正在尝试制作一个玩家有10艘战舰的战舰游戏。因此,我创建了一个struct Ship和一个由10个ships玩家组成的数组[10] 现在我想用10艘船来填充我的数组,所以我创建了一个函数addAllShips,它将返回一个包含10艘船的新数组,并将其分配给玩家[10]。但我得到了这个错误: main.c:34:17: error: array type 'Ship [10]' is not assignable playerShips = addAllShips() ~~~~~

我正在尝试制作一个玩家有10艘战舰的战舰游戏。因此,我创建了一个struct Ship和一个由10个ships玩家组成的数组[10]

现在我想用10艘船来填充我的数组,所以我创建了一个函数addAllShips,它将返回一个包含10艘船的新数组,并将其分配给玩家[10]。但我得到了这个错误:

main.c:34:17: error: array type 'Ship [10]' is not assignable
    playerShips = addAllShips()
    ~~~~~~~~~~~ ^
这是我的船结构

在这里,我主要是想填充我的玩家[10]阵列

这是我的addAllShips函数

Ship * addAllShips()
{
    Ship ships[10];

    for(int i = 0; i < 10; i++) {
        ships[i].rect.x = 123;
        ships[i].rect.y = 456;
        ships[i].rect.w = 789;
        ships[i].rect.h = 987;
        ships[i].isPlaced = true;
    }

    return ships;
}

现在我希望我的playerShips[10]数组包含10个Ship结构。

您不能返回和分配数组

相反,您应该将数组作为参数传递给initialize,它会自动转换为指向第一个元素的指针,并让函数使用传递的信息进行初始化

int main()
{
    Ship playerShips[10];

    addAllShips(playerShips);
}

void addAllShips(Ship *ships)
{

    for(int i = 0; i < 10; i++) {
        ships[i].rect.x = 123;
        ships[i].rect.y = 456;
        ships[i].rect.w = 789;
        ships[i].rect.h = 987;
        ships[i].isPlaced = true;
    }

}

在C中不能按值返回数组,因此此代码永远无法工作。addAllShips还返回一个悬空指针,一个指向超出范围的数组的指针。您的网站不再工作。此外,您不能在C中返回数组,而是可以通过内存引用它们,并对其进行更改。
Ship * addAllShips()
{
    Ship ships[10];

    for(int i = 0; i < 10; i++) {
        ships[i].rect.x = 123;
        ships[i].rect.y = 456;
        ships[i].rect.w = 789;
        ships[i].rect.h = 987;
        ships[i].isPlaced = true;
    }

    return ships;
}
int main()
{
    Ship playerShips[10];

    addAllShips(playerShips);
}

void addAllShips(Ship *ships)
{

    for(int i = 0; i < 10; i++) {
        ships[i].rect.x = 123;
        ships[i].rect.y = 456;
        ships[i].rect.w = 789;
        ships[i].rect.h = 987;
        ships[i].isPlaced = true;
    }

}