C/C++ >> Dynamic memory allocation
Posted by fabs on 16:16:00 05-04-2001
This is cool. Like in other languages, this function makes it possible to create the right amount of mem to hold a string at runtime! It's c++ code but it can easially be ported to c by using the malloc function.
To use this, just declare a char-pointer as your variable and do:
var = StrIn();
Enjoy!
fabs

//Start code
#include <iostream.h>
//I included string.h to make this simple.
//Use homemade-functions though
#include <string.h>

char * StrIn(void);

char * StrIn(void)
{
char buffer[128] , *ptr;

cin.getline(buffer,128);
int c= strlen(buffer)+1;
ptr= new char[c];
strcpy(ptr,buffer);
return ptr;
}
//EOC

[ This Message was edited by: fabs on 2001-05-04 16:18 ]