Introduction

The malloc() function is used to create an input buffer.

This technique avoids declaring and sizing an empty array.

The notation

char input[64]; 

can be replaced by this statement:

char *input; 

The size of the buffer is established inside the code by using the malloc() function.

Demo

#include <stdio.h> 
#include <stdlib.h> 

int main() //from   ww w .ja v a 2 s  .  c o  m
{ 
   char *input; 

   input = (char *)malloc(sizeof(char)*1024); 
   if(input==NULL) 
   { 
       puts("Unable to allocate buffer!"); 
       exit(1); 
   } 
   puts("Type something long:"); 
   fgets(input,1023,stdin); 
   puts("You wrote:"); 
   printf("\"%s\"\n",input); 

   return(0); 
}

Result

The fgets() function limits input to 1,023 bytes, leaving room left over for the \0 at the end of the string.

Related Topic