我正在尝试使用Jesse Liberty的“在24小时内自学C++”自己学习C++。我写了这个简短的程序来找出C++中的指针。试图理解C++中的指针
#include <iostream>
void hMany(int count); // hMany function prototype
void hMany(int count){
do {
std::cout << "Hello...\n";
count--;
} while (count >0);
};
int main (int argc, const char * argv[]) {
int counter;
int * pCounter = &counter;
std::cout << "How many hellos? ";
std::cin >> counter;
hMany(*pCounter);
std::cout << "counter is: " << counter << std::endl;
std::cout << "*pCounter is: " << *pCounter << std::endl;
return 0;
}
输出的结果是:
How many hellos? 2
Hello...
Hello...
counter is: 2
*pCounter is: 2
什么是传递指针(*的Pcounter)与参数(计数器)有什么好处?
任何帮助将不胜感激。 路易斯
更新:
确定。该程序正在工作,我现在完全理解C++指针。谢谢大家的回应。在尝试Chowlett的代码后,我得到了2个警告(不是错误)。一个是!没有以前的函数hMany和* pCount--的原型!表达结果未使用。我能够自己纠正原型,但我无法弄清* pCount--警告。
我问我的朋友托尼的帮助,这里是他的答案。
圆括号使事情按正确的顺序发生。
(*pCount)--
表示遵循指向它指向的整数的指针,然后递减整数,这就是你想要做的。
*pCount--
最后也做了错误的事情时,编译器将其视为
*(pCount—)
它说先递减指针,离开它指向“整数”你想改变一个之前(不存在这样的事情,因为你只有一个你称之为函数的整数),然后遵循这个递减的指针,并对该内存位置处的整数做任何事情。这就是编译器抱怨表达式结果未被使用的原因。编译器是正确的。此代码不正确地递减指针,提取错误的整数,并且不在任何地方存储错误的整数。
以下是可能感兴趣的C++新手的正确代码。
包括空隙hMany(INT * pCount); // hMany函数原型
空隙hMany(INT * pCount){// * pCount接收次数的地址
do {
std::cout << "Hello...\n";
// The parentheses make things happen in the correct order.
// says to follow the pointer to the integer it points to,
// and then decrement the integer.
(*pCount)--;
} while (*pCount >0);
}
INT主(INT的argc,常量字符* argv的[] ){
int counter;
int * pCounter = &counter;
std::cout << "How many hellos? ";
std::cin >> counter;
hMany(pCounter); // passing the address of counter
std::cout << "counter is: " << counter << std::endl;
std::cout << "*pCounter is: " << *pCounter << std::endl;
return 0;
}
_Pointers_ not _Points_。 – deepmax
请获得[*好*书](http://stackoverflow.com/q/388242/1171191)。 'C++'不是一种要在24小时内学习的语言。你只会学习那些难以忘却的可怕做法,并会给你一种对语言的不好印象。 – BoBTFish
我认为下面的答案缺少一些东西。在上面的代码中,没有指针被传递给函数。 – john