C:为什么您可以按值传递结构(而不​​是数组)(给函数)? [英] C: Why can you pass (to a function) a struct by value, but not an array?

查看:58
本文介绍了C:为什么您可以按值传递结构(而不​​是数组)(给函数)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背后有任何历史或逻辑原因吗?

Any historical or logical reasons behind it?

说明:当您将数组传递给C语言中的函数时,实际上实际上仅将指针传递给了数组.但是,传递结构时,可以传递该结构的副本或指针.

Explanation: when you pass an array to a function in C you actually only pass a pointer to an array. However, when you pass a struct, you can either pass a copy of the struct or the pointer.

//this:
int function(int array[10])
// is equivalent to this:
int function(int *array)
//and they both pass a pointer

//but this:
int function(struct tag name)
//passes a struct by value, where as this:
int function(struct tag *name)
//passes a pointer to it.

为什么有区别?

推荐答案

在原始K& R中,您无法按值传递结构.那是语法错误.由于许多编译器供应商将其作为扩展提供,因此按值传递最终进入了标准.

In the original K&R, you could not pass structs by value. That was a syntax error. Because many compiler vendors offered it as an extension, pass-by-value eventually made its way into the standard.

为什么要限制,为什么要进化?C语言开发的机器很小.段大小通常为64 KB.记忆是宝贵的,那么当您只需传递地址时,为什么还要复制某些内容呢?在堆栈上复制64字节结构 是一个错误,可能甚至不是用户想要的.

Why the restriction, and why the evolution? The machines that C was developed on were tiny. Segment sizes of 64 kilobytes were common. Memory was precious, so why copy something when you could just pass the address? Duplicating a 64-byte structure on the stack was an error, probably not even what the user intended.

到1990年代中期,这已不再是事实.32位寻址和4 MB或更大的RAM是常见的.限制是一个障碍,并导致了一些复杂性,因为如果没有 const ,则可以修改引用传递的结构,这可能是不经意的.

By the mid-1990s, that wasn't true anymore. 32-bit addressing and RAM of 4 MB or more were common. The restriction was a hinderance and led to some complexity, because without const a structure passed by reference could be modified, perhaps unwittingly.

为什么不对数组做同样的事情?没有需求.如您所知,数组和指针在C中紧密相关.C标准库在很大程度上取决于通过引用传递的方式,请考虑 memset strcpy .通过值传递结构意味着仅在调用中删除& ,而通过值传递数组将需要添加新的语法.一个提供按值按 作为C语法的编译器供应商会在会议之外被嘲笑.

Why not do the same with arrays? No demand. Arrays and pointers are closely related in C, as you know. The C standard library depends heavily on passing by reference, consider memset and strcpy. Whereas passing a struct by value meant just dropping the & on the call, passing an array by value would have entailed adding new syntax. A compiler vendor that offered, say, by value as C syntax would have been laughed out of the conference.

这篇关于C:为什么您可以按值传递结构(而不​​是数组)(给函数)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆