[英]Segmentation Fault while using rand() on C
So I've been getting an error while trying to pass a struct array to a function and assigning it random values所以我在尝试将结构数组传递给 function 并为其分配随机值时遇到错误
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++;
}
}
Your function prototype for setTrainDetails()
should include the type of the input parameter:您的
setTrainDetails()
的 function 原型应该包括输入参数的类型:
int setTrainDetails(train array[]);
Then when you call setTrainDetails()
in main()
, you should pass a pointer to the entire array.然后当你在
main()
中调用setTrainDetails()
时,你应该传递一个指向整个数组的指针。 C arrays decay into pointers when passed to a function, so you can just pass array
: C arrays 在传递给 function 时衰减为指针,因此您只需传递
array
:
train array[10]; // Declaring first array
setTrainDetails(array);
Passing array[10].id
is undefined behavior, because array
is only 10 train
s long, and C arrays start at index 0, so array[0]
- array[9]
are valid but array[10]
is no good.传递
array[10].id
是未定义的行为,因为array
只有 10 个train
长,并且 C arrays 从索引 0 开始,所以array[0]
- array[9]
有效但array[10]
不好。
train array[10];
declares an array of type train
that is 10 train
s long, but once the array is declared, array[10]
means index-10-of-the-array, which is out of bounds.声明一个长度为 10 个
train
的train
类型数组,但是一旦声明了数组, array[10]
表示 index-10-of-the-array,它超出了范围。
Inside the while
loop of setTrainDetails()
you have this line:在
setTrainDetails()
的while
循环中,您有以下行:
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.它实际上将列车编号设置为 100-199 之间的伪随机数,因为
rand() % 100
只能返回整数 0-99。 for random numbers between 100-200 inclusive , you would want rand() % 101 + 100
对于 100-200(含)之间的随机数,您需要
rand() % 101 + 100
Outside of that your code is fine除此之外,您的代码很好
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++;
}`
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.