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

2022/7/17 5:16:11

本文主要是介绍一个动态内存分配的数组--C和指针-动态内存分配习题,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

假设一个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     }
    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 }

 



这篇关于一个动态内存分配的数组--C和指针-动态内存分配习题的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程