簡體   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