09-06-2025

how to get the variable length string in C?

here is one of the solution


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

#include <stdlib.h>

char *get_string(){
int length = 0, capacity = 0;
int ch;
char *str = NULL;

while((ch = getchar()) != '\n' && ch != EOF){
if(length+1 > capacity){
capacity = (capacity == 0) ? 16 : capacity * 2;
char *temp = realloc(str, capacity);
if(temp == NULL){
free(str);
return NULL;
}
str = temp;
}
str[length++] = (char) ch;
}
if(str != NULL){
str[length] = '\0';
}
else{
str = calloc(1,sizeof(char));
if(str == NULL) return NULL;
}
return str;
}