-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArrayReallocation.c
More file actions
37 lines (30 loc) · 1009 Bytes
/
ArrayReallocation.c
File metadata and controls
37 lines (30 loc) · 1009 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
#include<stdio.h>
#include<stdlib.h>
char* getLine(void){
const size_t sizeIncrement = 10;
char* buffer = malloc(sizeIncrement);
char* currentPosition = buffer;
size_t maximumLength = sizeIncrement;
size_t length = 0;
char character;
if(currentPosition==NULL){return NULL;}
while(1){
character = fgetc(stdin);
if(character=='\n'){break;}
if(++length>=maximumLength){
char *newBuffer = realloc(buffer,maximumLength+=sizeIncrement);
if(newBuffer==NULL){
free(buffer);
return NULL;
}
currentPosition = newBuffer + (currentPosition-buffer);
buffer = newBuffer;
}
*currentPosition++=character;
}
*currentPosition = '\0';
return buffer;
}
void main(){
printf("\n%s\n",getLine());
}