我是 C 的新手,我正在阅读指针如何“指向”另一个变量的地址。所以我尝试了间接调用和直接调用,并收到了相同的结果(正如任何 C/C++ 开发人员所预测的那样)。这就是我所做的:
int cost;
int *cost_ptr;
int main()
{
cost_ptr = &cost; //assign pointer to cost
cost = 100; //intialize cost with a value
printf("\nDirect Access: %d", cost);
cost = 0; //reset the value
*cost_ptr = 100;
printf("\nIndirect Access: %d", *cost_ptr);
//some code here
return 0; //1
}
所以我想知道使用指针的间接调用是否比直接调用有任何优势,反之亦然?一些优点/缺点可能包括速度、执行操作所消耗的内存量(很可能相同,但我只是想把它放在那里)、安全性(如悬空指针)、良好的编程习惯等。
1有趣的是,我是使用 GNU C 编译器 (gcc),它仍然可以在没有 return 语句的情况下进行编译,并且一切都符合预期。可能是因为如果你忘记了 C++ 编译器会自动插入 return 语句。