arrayscmethods

Weird behaviour when passing array to method in C


I wrote a method that takes as parameters two stations and an array of railway trails.

typedef enum { MA1, MA2, MA3, MA4, MA5, MA6, MA7, 
    MA8, MA9, MA10, MA11, MA12, MA13, MA14, MA15, MA16} RailwayTrack;

typedef enum { S1, S2, S3, S4, S5, S6} RailwayStation;

typedef struct TrainData {
    int currentProgress;
    RailwayStation startStation;
    RailwayStation endStation;
    int railwayPathLength;
    RailwayTrack *railwayPath;
} TrainData;

#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;
}

The problem is that the array given as parameter won't get print out completely but just until the first 2 elements. You can see that as parameter I am passing an array of 4 elements but in the Logs only the first 2 are visible.

I was finally able to understand thanks to some help that I needed to pass the size of the array as parameter too. Thanks everyone for the help.


Solution

  • sizeof(railwayPath) is giving you the size of pointer not array in C. You do not pass the array, only reference (pointer to it).

    You need to pass size as a parameter:

    TrainData getTrainData(RailwayStation startStation, RailwayTrack railwayPath[],
                           size_t railwayPathSize, RailwayStation endStation) {