找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 280|回复: 1

Question 6.15:How can I declare local arrays of a size matching a passed-in array?

[复制链接]

210

主题

371

回帖

0

积分

管理员

积分
0
发表于 2013-7-8 11:15:59 | 显示全部楼层 |阅读模式
Q: How can I declare local arrays of a size matching a passed-in array?

A: Until recently, you couldn't; array dimensions in C traditionally had to be compile-time constants. However, C99 introduces variable-length arrays (VLA's) which solve this problem; local arrays may have sizes set by variables or other expressions, perhaps involving function parameters. (gcc has provided parameterized arrays as an extension for some time.) If you can't use C99 or gcc, you'll have to use malloc, and remember to call free before the
function returns. See also questions 6.14, 6.16, 6.19, 7.22, and maybe 7.32.     

210

主题

371

回帖

0

积分

管理员

积分
0
 楼主| 发表于 2013-7-8 11:27:11 | 显示全部楼层
问题:我如何声明一个和传入参数大小一样的局部数组?
回答:直到最近,这个才被允许。在传统的C语言中,数组的大小在编译的时候都必须是常数。可是在C99中引入了可变数组(VLA’s)来解决该问题;局部的数组可以通过变量和其他的表达式来确定其大小,也可以是函数的参数(gcc提供的参数化数组来作为扩展也有些时候了)。如果你不用gcc或者C99,那么你就得使用malloc函数了(可以参考问题6.14),但是要记得在函数返回之前调用free函数(参考问题6.14、6.16、6.19、7.22和7.32)。
个人建议最好不要使用可变数组和参数化数组的方式,如果要使用可变数组,那么就使用问题6.14中的malloc方式
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

果子博客
扫码关注微信公众号

Archiver|手机版|小黑屋|风叶林

GMT+8, 2026-2-1 13:56 , Processed in 0.093285 second(s), 20 queries .

Powered by 风叶林

© 2001-2026 Discuz! Team.

快速回复 返回顶部 返回列表