我正在尝试使用 Jesse Liberty 的“24 小时内自学 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) 与参数 (counter) 有什么好处?
任何帮助将不胜感激。路易斯
更新:
好的。该程序正在运行,我现在完全理解了 C++ 指针。谢谢大家的回复。在尝试了 Chowlett 的代码后,我收到了 2 个警告(不是错误)。一个是!函数 hMany 和 *pCount-- 没有以前的原型!表达式结果未使用。我能够自己更正原型,但我无法弄清楚 *pCount-- 警告。
我向我的朋友托尼寻求帮助,这是他的回答。
括号使事情以正确的顺序发生。
(*pCount)--
说跟随指向它指向的整数的指针,然后递减整数,这就是你想要做的。
*pCount--
最终做错事,编译器将其视为
*(pCount—)
它说首先递减指针,让它指向你想要改变的那个之前的“整数”(没有这样的事情,因为你只有一个你调用这个函数的整数),然后跟随这个递减的指针并且什么都不做与该内存位置的整数。这就是编译器抱怨表达式结果未使用的原因。编译器是正确的。此代码错误地递减指针,获取错误的整数,并且不会在任何地方存储该错误的整数。
对于那些可能感兴趣的 C++ 新手来说,这是正确的代码。
包括
无效 hMany(int *pCount); // hMany 函数原型
void hMany(int *pCount){ // *pCount 接收 count 的地址
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 main (int argc, const char * 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;
}