-1

I have a problem with the struct when storing data. I want to make a sentinel loop so please have a look and help me thank you.

#include<stdio.h>
#include<stdlib.h>
struct Vehichle
{
    char vecType[100];
    char plateNo[10];
    float hours;
};
struct Parking
{
  int parkNo ;
  // 1 =true 0=false
  int availability;

};
int main()
{   
  int c = 0;
  int x;
  struct Vehichle vehicle[c];
  struct Parking park[50];


  int counter = 1; 
  while(x!=-1)
  {
    printf("Enter -1 to end: \n");
    scanf("%d", &x);
    printf("Enter Vehicle Type etc: suv,mpv and more:");
    scanf("%d",&vehicle[x].vecType);
    printf("Please enter parking Number :");
    scanf("%d",&park[x].parkNo);

    park[x].availability = 1;

    counter++;  
  }
}

I expect that after it is stored in the struct, the program will loop.

Jake
  • 1,086
  • 12
  • 38
  • You never initialized `x`, so the first time through it could be anything, including -1. Change the declaration to something like `int x=0;` – Tom Karzes Jun 06 '19 at 18:34
  • Also, why are you declaring `vehicle[0]`? That serves no purpose, and you're clearly indexing out of bounds. – Tom Karzes Jun 06 '19 at 18:35
  • Maybe you should use that counter that you have, e.x declare an array with size Y and finish the loop when counter reaches Y. In case you don't know how big the array is going to be, you will have to use realloc upon reaching current array bounds. – Fanarosss Jun 06 '19 at 18:53
  • Read https://ericlippert.com/2014/03/05/how-to-debug-small-programs/ for tips on debugging your code. – Code-Apprentice Jun 06 '19 at 22:54

2 Answers2

2

There are a number of problems in your code. Here is your code where I have added some comments:

int main()
{   
  int c = 0;
  int x;                      // UPS: x is uninitialized
  struct Vehichle vehicle[c]; // UPS: c is zero so you don't get an array
  struct Parking park[50];


  int counter = 1; 
  while(x!=-1)                // UPS: Use of uninitialized x
  {
    printf("Enter -1 to end: \n");
    scanf("%d", &x);
    printf("Enter Vehicle Type etc: suv,mpv and more:");
    scanf("%d",&vehicle[x].vecType);             // UPS: vecType is char array so
                                                 // use %s instead of %d
                                                 // and don't use a &
    printf("Please enter parking Number :");
    scanf("%d",&park[x].parkNo);

    park[x].availability = 1;

    counter++;

  }
}

Besides that you have a problem when the user input is -1. The current code just continues and adds an element at index -1. That's illegal.

To fix add an extra line after the scanf. Like:

    scanf("%d", &x);
    if (x == -1) break;  // Stop the while loop

With that change you can do while(1) instead of while(x!=-1)

Some extra comments:

You should check that the user input (aka x) is within the valid range to be used as array index.

You should also check the return value of scanf. Like:

if (scanf("%d", &x) != 1)
{
    // Invalid input"
    ... error handling ...
}
Support Ukraine
  • 42,271
  • 4
  • 38
  • 63
0

(1) Below is an updated code as your code had several problems. I'm sure that looking at the below code, you would be able to understand the mistakes in your code. Feel free to use this as the base for writing your own version. (2) Please read the inline comments carefully. The comments elaborately explain the intention of that section of code (3) This is just a quick code. I've not compiled/run/tested this code. My intention is just to give you an idea about it with one possible example.

/* A very basic parking manager module

When a vehicle comes in for parking a)capture vehicle info & parking lot number where it is parking b)mark that lot as unavailable

When the vehicle is leaving the parking, capture parking lot number which is being emptied, and mark that lot as available

And, have some fun on the way. */

#include<stdio.h>
#define YOU_ARE_TRAPPED_BY_THE_BIG_BAD_GREEN_SCARY_MONSTER                                                                                                                       ({printf("HA HA HA, You didn't read and follow the inline comments !!\nNow stand up, jump 3 times, then sit down, and read all the comments again and do the min code modif to make me go away, else i won't let you escape the parking lot ... hoo ha ha ha ha >-)\n"); updateVehicleParkingInfo=1;})
#include<stdlib.h>


struct Vehichle{
    char vecType[100]; //type of vehicle eg suv,mpv and more...
    char plateNo[10];  //number plate of the vehicle
    float hours;       //???
};

struct Parking{
  int parkNo ; //parking lot num
  bool availability; //Is tbis parking space available? Yes/No
};

struct VehicleParkingInfo{
  struct Vehicle vehicle; //vehicle info
  struct Parking parking; //corresponding parking info
};

//maximum number of parking lots that the parking space has
#define MAX_PARKING_LOTS 10

//parking lot avaialble flags
#define PARKING_LOT_AVAILABLE true
#define PARKING_LOT_UNAVAILABLE false

//flags for vehicle coming in or leaving
#define VEHICLE_ENTERING true
#define VEHICLE_LEAVING false

void main(){
    int updateVehicleParkingInfo; //flag indicating that user wants to update parking info.
    int vehicleDirection; //flag for indicating whether the vehicle is coming in or going out of the parking
    int parkingIdx; //index of the parking lot to fetch values from.

    //array for info about all the parking lots
    struct VehicleParkingInfo vehicleParkingInfo[MAX_PARKING_LOTS];

    //initialize the parking & vehicle info of all the parking lots to zeros
    memset(vehicleParkingInfo,0,MAX_PARKING_LOTS*sizeof(VehicleParkingInfo));

    //for each parking lot, mark it as available and assign parking lot numbers serially
    for(parkingIdx = 0; parkingIdx < MAX_PARKING_LOTS; parkingIdx++){
        vehicleParkingInfo[parkingIdx].parking.parkNo = parkingIdx;
        vehicleParkingInfo[parkingIdx].parking.availability = PARKING_LOT_AVAILABLE;
    }

    //get user's input if parking info needs to be updated or it is time to close and go home
    printf("Update parking info? Enter 0 to end");
    scanf("%d",&updateVehicleParkingInfo);

    /*
    ****  SENTINEL LOOP  ****
    Continue updating the parking info until the user wants to even for unlimited number of times.
    Stop only when user enters a specific value i.e. 0.
    */
    while(updateVehicleParkingInfo != 0){

        printf("vehicle direction? 1 for entering, 0 for leaving:");
        scanf("%d",&vehicleDirection);

        if(vehicleDirection == VEHICLE_ENTERING){
            do{
                printf("Please enter parking Number:");
                scanf("%d",&parkingIdx);

                //*** CRASH ALERT!!! *** Following code can crash if parkingIdx is < 0, or >= MAX_PARKING_LOTS
                //TODO: (1) Add sanity check for parkingIdx (2) Add corrective steps if sanity check fails

                //if parking is not available, print an error message
                if(vehicleParkingInfo[parkingIdx].parking.availability == PARKING_LOT_UNAVAILABLE){
                    //TODO: change the below messages to fine-tune fun, humor, teasing etc levels (remember humor setting of TARS from Interstellar?)
                    printf("There is some other vehicle parked in this parking lot, please enter another parking lot number\n");
                    printf("BTW, I know which lots are available, but I won't tell you ... hehehe >-) \n, keep trying ...hoo hoo hooo\n");
                }
            //check if the requested parking lot is available, if yes, then take further actions, else request a new parking lot number
            }while(vehicleParkingInfo[parkingIdx].parking.availability == PARKING_LOT_UNAVAILABLE);

            printf("Yipee, this parking lot is available\n");

            //mark this parking lot number as being used so that another vehicle cannot come here.
            vehicleParkingInfo[parkingIdx].parking.availability = PARKING_LOT_UNAVAILABLE;

            //get vehicle type info and
            // *** CRASH ALERT!!! ***  The scanf below will crash if the user enters more 99+ characters (buffer overflow)
            // Best is to use fgets or getline with the stdin as the stream.
            // Ref https://stackoverflow.com/questions/4023895/how-do-i-read-a-string-entered-by-the-user-in-c
            // TODO: Replace below scanf() with a better/safer implmentation
            printf("Enter Vehicle Type etc: suv,mpv and more:");
            scanf("%s",vehicleParkingInfo[parkingIdx].vehicle.vecType);

            //TODO: other steps.
        }

        if(vehicleDirection == VEHICLE_LEAVING){
            do{
                printf("Please enter parking Number:");
                scanf("%d",&parkingIdx);

                //*** CRASH ALERT!!! *** Following code can crash if parkingIdx is < 0, or >= MAX_PARKING_LOTS
                //TODO: (1) Add sanity check for parkingIdx (2) Add corrective steps if sanity check fails

                //if parking is available, print an error message
                if(vehicleParkingInfo[parkingIdx].parking.availability == PARKING_LOT_AVAILABLE){
                    printf("It appears that the parking lot number is incorrect, please enter correct parking lot number\n");
                }
            //check if the requested parking lot is available, if yes, then request a new parking lot number, else proceed further
            }while(vehicleParkingInfo[parkingIdx].parking.availability == PARKING_LOT_AVAILABLE);

            printf("Bye bye, drive safely\n");

            //mark this parking lot number as available for other incoming vehicles.
            vehicleParkingInfo[parkingIdx].parking.availability = PARKING_LOT_AVAILABLE;
        }

        //get user's input if parking info needs to be updated or it is time to close and go home
        printf("Update parking info? Enter 0 to end");
        scanf("%d",&updateVehicleParkingInfo);

        //TODO: remove the following line of code before running the program
        YOU_ARE_TRAPPED_BY_THE_BIG_BAD_GREEN_SCARY_MONSTER;

        //go back to while loop,
        //check if the vehicle parking info needs to be updated,
        //break if the user has entered 0

    }//end of the Sentinel loop

    //the above loop will run indefinitely. The user has quite a lot of ways to come out of the loop
    //(1) Enter the sentinel value '0', (easiest path)
    //(2) Somehow stop the program e.g. by banging his/her head really hard on the computer such that computer breaks .. etc


}//end of main()
ARD
  • 48
  • 8