duryodhan -
Yes, "allocation" is necessary.
And no, you don't necessarily need "malloc()" just to allocate space. As DMail's example shows.
Here are three equivalent examples:
Code:
#include <stdio.h>
#include <string.h>
#include <malloc.h>
#define MAXCHAR 20
char *
trim (char *s)
{
s[strlen(s)-1] = '\0';
return s;
}
void
get_value (char *s, int maxlen)
{
fgets (s, maxlen, stdin);
printf ("s= %s...\n", trim(s));
}
int
main (int argc, char *argv[])
{
char *s1 = NULL, *s2 = NULL, s3[MAXCHAR+1];
s1 = (char *)malloc (MAXCHAR+1);
if (s1)
{
get_value (s1, MAXCHAR);
free (s1);
s1 = NULL;
}
s2 = new char[MAXCHAR+1];
if (s2)
{
get_value (s2, MAXCHAR);
delete[] s2;
s2 = NULL;
}
get_value (s3, sizeof (s3));
return 0;
}
Here's a sample compile/execute:
Quote:
g++ -g -o x x.cpp
./x
abc
s= abc...
def
s= def...
123
s= 123...
|
'Hope that helps .. PSM