我想做的是,当 harePosition 的值小于 1 时,我希望它正好等于 1。但是当我打印该值时,它给了我负值。
我对指针不太有经验,我确信是我缺乏理解导致了我的问题。
int main()
{
int *harePosition = 1, *tortoisePosition = 1;
bool running = 1;
char *sameSpot = "OUCH!!!";
printRace();
srand(time(NULL)); //Allows rand() to create random numbers
while(running){
harePosition = moveHare(harePosition); //calls the function to determine what action will be taken
printf("Hare Position is: %d\n", harePosition); //prints to the screen, I'm using this to troubleshoot if the issue was resolved.
tortoisePosition = tortoiseMove(tortoisePosition);
int *moveHare(unsigned int *harePosition) // function where the issue is happening
{
int hareAction;
hareAction = rand () % 10; // randomly picks a number
if(hareAction < 2){ // based on the hareAction chooses one of the if statements and preforms a math operation
harePosition = harePosition;
}
else if(hareAction > 1 && hareAction < 4){
harePosition += 9;
}
else if(hareAction == 4){
harePosition -= 12;
}
else if(hareAction > 4 && hareAction< 8){
harePosition += 1;
}
else{
harePosition -= 2;
}
if(harePosition < 1){ // Suppose to prevent the harePosition from being less than one
return = 1;
}
return harePosition;
}
最佳答案
int *harePosition = 1;
将创建一个指针并使其指向内存位置1(a)。这不是您需要的。
事实上,您的代码中完全不需要使用指针,因为您传入了值并返回了新值(b)。因此,以更简单的形式,您需要的是:
int fn (int someVal) {
return someVal + 42;
}
int val = 7;
val = fn (val); // now it will be 49.
<小时/>
(a) 至少在允许的系统中。我认为这个语句至少应该生成某种诊断消息,因为正如 ISO C11 简单赋值
在其约束中指出的那样,您应该只分配一个兼容指针或空指针,不是某个任意整数。
(b) 一般来说,传入指针的唯一原因是在没有指针的语言中模拟按引用传递。我真诚地希望在某个时候 ISO 能够硬着头皮向该语言添加真正的引用传递。那么大约 80% 的 C 问题就会消失:-)
如果您确实需要通过(模拟)引用传递它,则必须确保区分指针和值 它指向。例如:
void fn (int *pSomeVal) { // Receive a POINTER to an int.
*pSomeVal += 42; // Update the thing it points TO.
}
int val = 7;
fn (&val); // Pass POINTER to the int,
// then val becomes 49.
关于c - C 中的指针给出负值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54818593/