我第二次进行了这项工作,但不小心将其破坏了。谁能帮我解决这个问题?我遇到了分段错误,所以我假设我在某个时候弄乱了指针。它应该根据用户输入生成一堆随机数。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
unsigned int mySeed; // creates our variables
unsigned int taps[2];
unsigned int temp[2];
unsigned int myToggle;
FILE *fp;//opens the file
fp = fopen("random.txt", "w");//sets the file to open equal to this file
int TapInputs = 1;
int count = 0;
int tap;
int myNewNumber = 0;
mySeed = atoi(argv[1]);
if(atoi(argv[1]) > 0) //Error checking for negative inputs.
{
printf("Please enter the taps you'd like to use : ");//prompts user to input the taps and then makes sure theyre in range
while(TapInputs)
{
scanf("%d",&tap);
if((tap > 0)&&(tap < 33))
{
*(taps+count)=tap;
}
else if(tap == -1) // when we find -1 we do this
{
TapInputs = 0;
}
else if(tap > 32)
{
exit(0);
}
count++;
}
printf("How many numbers do you want to generate: "); //prompts user to input the number of numbers to use
scanf("%d", &myNewNumber);
while (myNewNumber < 0)// error checking for positive inputs
{
printf("How many numbers do you want to generate: ");
scanf("%d", &myNewNumber);
}
printf("\nRandom Numbers:");
while(myNewNumber)//creates number equal to the user input number in the previous step
{
temp[0] = mySeed; // makes temp1 the seed
temp[1] = mySeed; // makes temp2 the seed
temp[0] = (temp[0] >> taps[0]) & 1; // checks and sets the bit
temp[1] = (temp[1] >> taps[1]) & 1; // checks and sets the bit
myToggle = (temp[0] ^ temp[1]); // here we xor the temp1 and 2
mySeed = (mySeed << 1) ^ myToggle; // use bittoggle to shift the seed and generate a new number
fprintf(fp, "%d\r\n", mySeed); // wrties the generated number into the file
printf("\n%d", mySeed); // prints the number
myNewNumber -= 1;
}
fclose(fp); // closes file, creates a new line and returns 0 to the fucntion
printf("\n");
return 0;
}
else
{ // if the number the user input was 0 we will end our program
exit(0);
}
}
故障在执行后立即发生。
最佳答案
这段代码:
while(TapInputs)
{
scanf("%d",&tap);
if((tap > 0)&&(tap < 33))
{
*(taps+count)=tap;
}
else if(tap == -1) // when we find -1 we do this
{
TapInputs = 0;
}
else if(tap > 32)
{
exit(0);
}
count++;
}
执行直到找到
TapInputs
为false
或换句话说0
。仅当您将-1
作为scanf("%d", &tap)
的输入时,才会发生这种情况。在此之前,您将继续阅读并增加count
。但是上面的几行,您已经声明
unsigned int taps[2];
在你的
while
循环中*(taps+count)=tap;
因此,如果您已经阅读了足够多的
tap
并一直在0
和33
之间找到它,直到找到-1
,count
的数量就会增加到足以使您的数组超出范围。关于c - 需要帮助解决段错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36761514/