-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstring.c
More file actions
43 lines (40 loc) · 993 Bytes
/
string.c
File metadata and controls
43 lines (40 loc) · 993 Bytes
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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void read_dynamic_string(char **str) {
if(*str != NULL) free(*str);
int capacity = 10;
int length = 0;
char ch;
*str = malloc(capacity * sizeof(char));
if(*str == NULL) return;
while((ch = getchar()) != '\n'){
if(length + 1 >= capacity){
capacity += 10;
char *new_str = realloc(*str, capacity * sizeof(char));
if(new_str == NULL){
free(*str);
*str = NULL;
return;
}
*str = new_str;
}
(*str)[length++] = ch;
}
(*str)[length] = '\0';
}
int main() {
char *str = NULL;
printf("Enter a string: ");
read_dynamic_string(&str);
if(str != NULL) {
printf("You entered: %s\n", str);
// free(str);
}
read_dynamic_string(&str);
if(str != NULL) {
printf("You entered: %s\n", str);
// free(str);
}
return 0;
}