-
pointer problem
hi there, there's something wrong with this statements : i guess there's a pointer problem. i need to getdata from other function prototype , and then transfer to the main prototype ..l pls help me to correct it ....
Code:
int main ()
{
/* local definition */
// NUM_STACK num_start;
// OP_STACK op_start;
char *input;
getInfo(&input);
printf ("\nthe 6th of the char is ... %c\n", *(input+5));
printf ("the answer is %s\n\n", input);
return 0;
}
void getInfo (char *getdata)
{
*getdata = (char*)malloc(100);
printf ("Please enter the value > ");
scanf ("%[^\n]", *getdata);
}
-
Code:
void getInfo (char **getdata)
{
*getdata = (char*)malloc(100);
printf ("Please enter the value > ");
scanf ("%[^\n]", *getdata);
}
-
Some extra error checking might be usefull:
Make the getInfo function return a char * so you can check if the malloc function failed:
Code:
char * getInfo (char **getdata)
{
if((*getdata = (char*)malloc(100)) != NULL)
{
printf ("Please enter the value > ");
scanf ("%[^\n]", *getdata);
}
return (*getdata);
}
Check the return value of getInfo and check the length of the string:
Code:
if(getInfo(&input) == NULL)
return -1;
if(strlen(input) > 5)
printf ("\nthe 6th of the char is ... %c\n", *(input+5));
Free the allocated memory at the end of main.
The scanf function is not the best function to read from input (not safe). It's better to use the fgets function instead.
-