[英]Pointer in C giving negative values
我想做的是,當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 Simple assignment
在其約束中指出的那樣,您應該僅分配兼容的指針或空指針, 而不是任意的整數。
(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.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.