Repository navigation
Expand file tree
/
Copy path3_inc_array_size.c
More file actions
78 lines (58 loc) · 1.68 KB
/
Copy path3_inc_array_size.c
File metadata and controls
78 lines (58 loc) · 1.68 KB
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include <stdio.h>
#include <stdlib.h>
void print_array(int* a, int size){
for(int i = 0; i < size; ++i){
printf("%d ",a[i]); // or *(a+i)
}
printf("\n");
}
int* insert(int *a,int* size,int position,int value){
*size += 1;
int* temp = realloc(a,(*size)*sizeof(int));
if(temp == NULL){
//free(a)
//exit(1);
// If realloc fails, temp is NULL. We must not free the original 'a' here,as 'main' still holds the pointer to it.
// Instead, we restore the original size and return the original 'a' pointer.
// 'main' will detect this failure because 'size' hasn't changed.
*size -= 1;
return a;
}
a = temp;
for(int i = (*size) - 1; i > (position - 1); i--){
a[i] = a[i-1];
}
a[position-1] = value;
return a;
}
int main(void){
int size;
printf("Enter the size of your desired array: ");
scanf("%d",&size);
printf("Enter %d elemtnts ->\n",size);
int* a = malloc(sizeof(int)*size);
if(a == NULL){
return 1;
}
for(int i = 0; i < size; ++i){
printf("\t\t%d]Enter a number: ",i+1);
scanf("%d",&a[i]); // or a+i
}
print_array(a,size);
int value,position;
printf("Enter new number that you wanna add to the array: ");
scanf("%d",&value);
do{
printf("Enter the position at Which you wanna add given number: ");
scanf("%d",&position);
}while(position > size + 1 || position < 1);
int old_size = size;
a = insert(a,&size,position,value);
if(size == old_size){
free(a);
printf("realloc faild!!");
return 3;
}
print_array(a,size);
free(a);
}