北大C语言高级编程 动态数组.ppt

  1. 1、有哪些信誉好的足球投注网站(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。。
  2. 2、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载
  3. 3、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
动态数组 #include stdio.h int main(){ int n; scanf(“%d”, n); int shzu[n]; … … return 0; } #include stdio.h #include malloc.h int main(){ int n; scanf(“%d”, n); int *shzu = (int *) malloc(sizeof(int) * n); … … free(shuzu); return 0; } 动态数组 #include stdio.h int main(){ int n; scanf(“%d”, n); double shzu[n]; … … return 0; } #include stdio.h #include malloc.h int main(){ int n; scanf(“%d”, n); double *shzu = (double *) malloc(sizeof(double) * n); … … free(shuzu); return 0; } 关于malloc()/free()的使用 别忘了: #include malloc.h malloc函数的参数为所需申请内存的大小:以字节为单位 malloc函数返回一个void*类型的地址,必须通过强制类型转换,才能赋值给特定的指针变量: int * pint = (int *) malloc( ... ); 用malloc函数生成各种类型的动态数组,最好使用“sizeof(类型名) * 动态数组长度”形式确定分配内存的大小: int * pint = (int *) malloc( sizeof(int) * 100 ); 分配的内存不再使用时一定要释放: free(pint); 动态数组 malloc()在内存中分配的一块连续的内存区域,这与静态数组在内存中的布局是一样的。因此,指向这块内存区域的指针变量就可以像数组一样使用了: int *pint; pint = (int *)malloc(sizeo(int)*10); pint[0], pint[1], ……, pint[9] 在使用动态数组时,一定要注意不要越界引用,即不要引用并没有分配给你使用的内存: 当引用pint[10] 时,对于C语言来说,这是合法的,但是它所引用的却是所分配的内存区域之外的其他内存区域,其内的值是未知的;如果对其进行修改的话,还可能影响整个程序的正确性。 5 6 7 8 9 0 1 2 3 4 10(?) ? pint pint+10 #include stdio.h #define N 10 void compute(int distance); int main(){ int n; int distance[N]; int i; scanf(%d, n); for(i = 0; i n; i++){ scanf(%d, (distance[i])); } for(i = 0; i n; i++){ compute(distance[i]); } return 0; } #include stdio.h #include malloc.h void compute(int distance); int main(){ int n; int i; scanf(%d, n); int *distance = (int *) malloc(sizeof(int)*n); for(i = 0; i n; i++){ scanf(%d, (distance[i])); } for(i = 0; i n; i++){ compute(distance[i]); } free(distance); return 0; } 问题4: 跳绳游戏 关键信息: 计算1分钟内跳了多少下绳; 1秒钟跳1次; 跳坏后,3秒钟后才能又开始跳; 输入、输出 示例 = 60 – 3 * 3 = 60 – 1 * 3 = 60 – 4 * 3 = 60 – 4 * 3 = 47 = 60 – 0 * 3 输入:0 输出:60 0秒 60秒 y秒 在y秒时,小朋友停止了跳绳 60下 输入:3 12 23 45 输出:51 0秒 60秒 12下 12秒 15秒 12下 26秒 23下 29秒 23下 45下 51秒 54秒 45下 y秒 在y秒时,小朋友停止了跳绳 51 = 60 – 3*3 输入:1 17 输出:57 0秒 60秒 17秒 17下 20秒 17下 y秒 在y秒时,小朋友停止了跳绳 57 = 60 – 1*3 输入:4

文档评论(0)

a13355589 + 关注
实名认证
内容提供者

该用户很懒,什么也没介绍

1亿VIP精品文档

相关文档