繁体   English   中英

在 C 上使用 rand() 时出现分段错误

[英]Segmentation Fault while using rand() on C

所以我在尝试将结构数组传递给 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++;
    }
}

您的setTrainDetails()的 function 原型应该包括输入参数的类型:

int setTrainDetails(train array[]);

然后当你在main()中调用setTrainDetails()时,你应该传递一个指向整个数组的指针。 C arrays 在传递给 function 时衰减为指针,因此您只需传递array

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

传递array[10].id是未定义的行为,因为array只有 10 个train长,并且 C arrays 从索引 0 开始,所以array[0] - array[9]有效但array[10]不好。

train array[10]; 声明一个长度为 10 个traintrain类型数组,但是一旦声明了数组, array[10]表示 index-10-of-the-array,它超出了范围。

setTrainDetails()while循环中,您有以下行:

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

它实际上将列车编号设置为 100-199 之间的伪随机数,因为rand() % 100只能返回整数 0-99。 对于 100-200()之间的随机数,您需要rand() % 101 + 100

除此之外,您的代码很好

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM