我正在学习使用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