我编写了一个方法,以两个车站和一组铁路路线为参数。
#define MAP1_TRAIN_N1 getTrainData(S1, (RailwayTrack[]){ MA1, MA2, MA3, MA8 }, S6)
TrainData getTrainData(RailwayStation startStation, RailwayTrack railwayPath[] /*ERROR HERE?*/, RailwayStation endStation) {
TrainData trainData;
trainData.startStation = startStation;
for (int i = 0; i < sizeof(railwayPath)/sizeof(RailwayTrack); i++)
{
printf("Eli: %d\n",railwayPath[i]);
}
//OUTPUT: Eli0, Eli1
RailwayTrack test[] = { MA1, MA2, MA3, MA8 }; //TEST ARRAY CAUSE ABOVE IS NOT WORKING
for (int i = 0; i < sizeof(test)/sizeof(RailwayTrack); i++)
{
printf("Eli: %d\n",test[i]);
}
//OUTPUT: Eli0, Eli1, Eli2, Eli3
trainData.railwayPath = railwayPath;
trainData.endStation = endStation;
return trainData;
}
问题是作为参数给出的数组不会完全得到调试,而是直到第二个元素为止。看起来第一种情况下识别的大小是 2 而不是 4。
我尝试添加调试,但我不知道为什么代码会这样
sizeof(railwayPath)
给你的是指针的大小,而不是C中的数组。你不传递数组,只传递引用(指向它的指针)。
您需要传递尺寸作为参数:
TrainData getTrainData(RailwayStation startStation, RailwayTrack railwayPath[],
size_t railwayPathSize, RailwayStation endStation) {