C 中的直接调用与间接调用
我是 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语句。
I am new to C and I was reading about how pointers "point" to the address of another variable. So I have tried indirect invocation and direct invocation and received the same results (as any C/C++ developer could have predicted). This is what I did:
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
}
So I am wondering if indirect invocation with pointers has any advantages over direct invocation or vice-versa? Some advantages/disadvantages could include speed, amount of memory consumed performing the operation (most likely the same but I just wanted to put that out there), safeness (like dangling pointers) , good programming practice, etc.
1Funny thing, I am using the GNU C Compiler (gcc) and it still compiles without the return statement and everything is as expected. Maybe because the C++ compiler will automatically insert the return statement if you forget.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
间接调用和直接调用用在不同的地方。在您的示例中,首选直接调用。使用指针的一些原因:
Indirect and direct invocation are used in different places. In your sample the direct invocation is prefered. Some reasons to use pointers:
指针表示法涉及两次内存读取(或一次读取和一次写入),而直接调用则涉及一次。
由于内存访问速度很慢(与寄存器中的计算相比;与磁盘上的访问相比快),因此指针访问会减慢速度。
然而,有时只有一个指针可以让你做你需要做的事情。不要纠结于差异,在需要时一定使用指针。但在不需要时避免使用指针。
The pointer notation involves two memory fetches (or one fetch and one write) where the direct invocation involves one.
Since memory accesses are slow (compared to computation in registers; fast compared to access on disk), the pointer access will slow things down.
However, there are times when only a pointer allows you to do what you need. Don't get hung up on the difference and do use pointers when you need them. But avoid pointers when they are not necessary.
在“printf(..., *cost)”情况下,“cost”的值被复制到堆栈中。虽然在这种情况下微不足道,但想象一下如果您正在调用不同的函数并且“cost_ptr”指向一个多兆字节数据结构。
In the "printf(..., *cost) case, the value of "cost" is copied to the stack. While trivial in this instance, imagine if you were calling a different function and "cost_ptr" pointed to a multi-megabyte data structure.