我正在學習使用switch語句並使用rand()和srand()函數,但當我嘗試運行此代碼時,出現了分段錯誤,我從本書中獲得了我正在從中學習C 。什麼可能導致這種情況發生?爲什麼運行此代碼時出現分段錯誤?
#include <stdio.h>
int main(void)
{
int iRandomNum = 0;
srand(time());
iRandomNum = (rand() % 4) + 1;
printf("\nFortune Cookie - Chapter 3\n");
switch (iRandomNum) {
case 1:
printf("\nYou will meet a new friend today.\n");
break;
case 2:
printf("\nYou will enjoy a long and happy life.\n");
break;
case 3:
printf("\nOpportunity knocks softly. Can you hear it?\n");
break;
case 4:
printf("\nYou'll be financially rewarded for your good deeds.\n");
break;
} //end switch
printf("\nLucky lotto numbers: ");
printf("%d ", (rand() % 49) + 1);
printf("%d ", (rand() % 49) + 1);
printf("%d ", (rand() % 49) + 1);
printf("%d ", (rand() % 49) + 1);
printf("%d ", (rand() % 49) + 1);
printf("%d\n", (rand() % 49) + 1);
} //end main function
在seg故障之前控制檯上是否出現了任何問題?基本上,你有沒有得到任何printf語句顯示? –
確保你[編譯調試標誌](http://gcc.gnu.org/onlinedocs/gcc/Debugging-Options.html)(通常是'-g'),然後使用['gdb']運行你的程序。 (http://www.gnu.org/s/gdb/)來找出究竟是哪一行seg故障發生。 –
@adam在分段錯誤之前沒有任何東西出現,我編譯時沒有錯誤,然後當我運行它時,它說分段錯誤。 – nastyn8