ICode9

精准搜索请尝试: 精确搜索
首页 > 系统相关> 文章详细

一个动态内存分配的数组--C和指针-动态内存分配习题

2022-07-16 13:34:50  阅读:203  来源: 互联网

标签:count 数组 int 分配 exit 动态内存 习题 array size


假设一个int类数组,需要在程序运行中中进行动态内存分配。

将首先使用malloc(),进行分配。

 

数组的首元素,代表除本身外,数组还有多少个元素。

例如,首元素为3,则代表数组应当具有4个元素。

 

同时要求,如果其余元素的个数与首元素的值不匹配时,需要对该数组的内存进行动态调整。

使用realloc()函数进行内存块的扩展或缩减。

 

以下为程序代码:

 1 # include <stdio.h>
 2 # include <stdlib.h>
 3 # include <ctype.h>
 4 
 5 int main()
 6 {
 7     int size;
 8     int* array;
 9     puts("The limit of the array");
10     if (scanf("%d", &size) == 1 && size >= 1)
11     {
12         array = (int*)malloc((size +1)* sizeof(int));
13         if (array != NULL)
14             *array = size;
15         else
16             exit(1);
17     }
18     else
19     {
20         puts("Illegal number for the size of array.");
21         exit(1);
22     }
23 
24 
25     int count = 0;
26     int value;
27     while (scanf("%d",&value)== 1)
28     {
29         count+=1;
30         if (count > size)
31         {
32             array = (int*)realloc(array, (count + 1) * sizeof(int));
33             if (array == NULL)
34             {
35                 puts("Memory fail.");
36                 exit(1);
37             }
38         }
39         array[count] = value;    
40     }
41 42 if (count < size) 43 array =(int*) realloc(array, (count + 1) * sizeof(int)); 44 if (array == NULL) 45 { 46 puts("Memory fail"); 47 exit(1); 48 } 49 50 array[0] = count; 51 52 53 for (int i = 0; i < (count+1); i++) //打印测试 54 { 55 printf("%d ", array[i]); 56 } 57 58 59 free(array); 60 61 return 0; 62 63 }

 

标签:count,数组,int,分配,exit,动态内存,习题,array,size
来源: https://www.cnblogs.com/muyangbeihai/p/16483976.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有