-
Notifications
You must be signed in to change notification settings - Fork 0
/
insertarray1.c
51 lines (43 loc) · 1.06 KB
/
insertarray1.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
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char **names = malloc(3 * sizeof(char *));
int capacity = 3; // Initial capacity of the array
int n, l;
if (names == NULL)
{
printf("Memory allocation failed.");
return 1;
}
for (n = 0;; n++)
{
if (n >= capacity)
{
capacity *= 2; // Double the capacity
char **temp = realloc(names, capacity * sizeof(char *));
if (temp == NULL)
{
printf("Memory reallocation failed.");
break;
}
names = temp;
}
printf("Enter the name of your friend (or 'quit' to exit): ");
names[n] = malloc(100);
scanf("%s", names[n]);
if (strcmp(names[n], "quit") == 0)
{
free(names[n]);
break;
}
}
for (l = 0; l < n; l++)
{
printf("%s\n", names[l]);
free(names[l]); // Free the allocated memory
}
free(names); // Free the array of pointers
return 0;
}