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

Question 6.14:How can I set an array's size at run time?

[复制链接]

210

主题

371

回帖

0

积分

管理员

积分
0
发表于 2013-7-8 10:43:07 | 显示全部楼层 |阅读模式
Q: How can I set an array's size at run time? How can I avoid fixed-sized arrays?

A: The equivalence between arrays and pointers (see question 6.3) allows a pointer to malloc'ed memory to simulate an array quite effectively.After executing
#include <stdlib.h>
int *dynarray;
dynarray = malloc(10 * sizeof(int));
(and if the call to malloc succeeds), you can reference dynarray (for i from 0 to 9) almost as if dynarray were a conventional, statically-allocated array (int a[10]). The only difference is that sizeof will not give the size of the ``array&#39;&#39; (see question 7.28. See also questions 1.31b, 6.16, 7.7, and 7.29.

0

主题

5

回帖

0

积分

新手上路

积分
0
发表于 2013-7-8 10:51:03 | 显示全部楼层
纳尼  我们看不懂

210

主题

371

回帖

0

积分

管理员

积分
0
 楼主| 发表于 2013-7-8 11:00:20 | 显示全部楼层
问题:我如何在程序运行的时候来设定数组的大小?怎么样避免固定的数组的大小?
回答:数组和指针之间“等价”的特性(参考问题6.3)允许指针指向分配了内存的空间,这样可以有效的模拟一个数组。执行了下面的程序后
       #include <stdlib.h>
            int *dynarray;
            dynarray = malloc(10 * sizeof(int));
(如果malloc函数调用成功),你几乎可以把它当做是一个常规的、静态分配内存的数组(int[10])来引用dynarry。唯一的区别是sizeof将不会给出数组的大小(参考问题7.28。也可以参考问题1.31b,6.16,7.7和7.29)。

210

主题

371

回帖

0

积分

管理员

积分
0
 楼主| 发表于 2013-7-8 11:02:16 | 显示全部楼层

回 beyond97 的帖子

beyond97:纳尼  我们看不懂 (2013-07-08 10:51)
我在后面会给出我的翻译和自己的理解的
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

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

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

GMT+8, 2026-2-1 12:26 , Processed in 0.081724 second(s), 20 queries .

Powered by 风叶林

© 2001-2026 Discuz! Team.

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