-
Notifications
You must be signed in to change notification settings - Fork 0
/
8-list_malloc.c
57 lines (47 loc) · 894 Bytes
/
8-list_malloc.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <stdio.h>
#include <stdlib.h>
/**
* main: Dynamically allocate an array of size 3
*
* Return: no return.
*/
int main(void)
{
//Dynamically allocate an array of size 3
int *list=malloc(3*sizeof(int));
if(list==NULL)
{
return 1;
}
//Assign 3 numbers to that array
list[0]=1;
list[1]=2;
list[2]=3;
//Time passe
//Allocate new array of size 4
int *tmp=malloc(4*sizeof(int));
if(tmp==NULL)
{
free(list);
return 1;
}
//Copy numbers from old array into new array
for (int i=0;i<3;i++)
{
tmp[i]=list[i];
}
//Add fourth number to new array
list[3]=4;
//Free old array
free(list);
//Remember new array
list=tmp;
//Print new array
for (int i=0;i<4;i++)
{
printf("%i\n",list[i]);
}
//Free new array
free(list);
return 0;
}