Moh*_*nde 1 c comparison pointers indirection invocation
我是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
}
Run Code Online (Sandbox Code Playgroud)
所以我想知道使用指针的间接调用是否比直接调用有任何优势,反之亦然?一些优点/缺点可能包括速度,执行操作所消耗的内存量(很可能相同,但我只想把它放在那里),安全性(如悬挂指针),良好的编程习惯等
.1有趣的是,我是使用GNU C编译器(gcc),它仍然编译没有return语句,一切都按预期.也许是因为如果你忘了,C++编译器会自动插入return语句.
间接和直接调用用于不同的地方.在您的示例中,首选直接调用.使用指针的一些原因:
| 归档时间: |
|
| 查看次数: |
2795 次 |
| 最近记录: |