Home > OS >  Segmentation Fault while using rand() on C
Segmentation Fault while using rand() on C

Time:08-09

So I've been getting an error while trying to pass a struct array to a function and assigning it random values

typedef struct {
    int id;
    time_t t; //Variable t is of the type time - this allows us to store date&time
}
train;

int setTrainDetails();

int main() {
    train array[10]; // initializing first array
    setTrainDetails(array[10].id);
}

int setTrainDetails(train array[10]) {
    srand((unsigned) time(NULL));
    int count = 0;
    while (count < 10) {
        array[count].id = rand() % 100   100; // set train number from 100-200
        count  ;
    }
}

CodePudding user response:

Your function prototype for setTrainDetails() should include the type of the input parameter:

int setTrainDetails(train array[]);

Then when you call setTrainDetails() in main(), you should pass a pointer to the entire array. C arrays decay into pointers when passed to a function, so you can just pass array:

train array[10]; // Declaring first array
setTrainDetails(array);

Passing array[10].id is undefined behavior, because array is only 10 trains long, and C arrays start at index 0, so array[0]-array[9] are valid but array[10] is no good.

train array[10]; declares an array of type train that is 10 trains long, but once the array is declared, array[10] means index-10-of-the-array, which is out of bounds.

Inside the while loop of setTrainDetails() you have this line:

array[count].id = rand() % 100   100; // set train number from 100-200

which actually sets train number to a pseudo-random number between 100-199, since rand() % 100 can only return integers 0-99. for random numbers between 100-200 inclusive, you would want rand() % 101 100

Outside of that your code is fine

CodePudding user response:

typedef struct {
    int id;
    time_t t; //Variable t is of the type time - this allows us to store date&time
}
train;

int setTrainDetails();

int main() {
    train array[10]enter code here; // initializing first array
    setTrainDetails(array);
}

int setTrainDetails(train array[10]) {
    srand((unsigned) time(NULL));
    int count = 0;
    while (count < 10) {
        array[count].id = rand() % 100   100; //
        count  ;
    }`
   
}
  • Related