Thread: pointer problem

  1. #1
    ~- Y u n a -~ beely's Avatar
    Join Date
    Dec 2001
    Posts
    291

    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);
    }

  2. #2
    Me want cookie! Monster's Avatar
    Join Date
    Dec 2001
    Posts
    680
    Code:
    void getInfo (char **getdata)
    {
    	*getdata = (char*)malloc(100);
    
    	printf ("Please enter the value > ");
    	scanf ("%[^\n]", *getdata);
    }

  3. #3
    Me want cookie! Monster's Avatar
    Join Date
    Dec 2001
    Posts
    680
    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.

  4. #4

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. pointer to pointer realloc problem
    By prakash0104 in forum C Programming
    Replies: 14
    Last Post: 04-06-2009, 08:53 PM
  2. Another pointer problem
    By mikahell in forum C++ Programming
    Replies: 21
    Last Post: 07-20-2006, 07:37 PM
  3. Pointer problem
    By mikahell in forum C++ Programming
    Replies: 5
    Last Post: 07-20-2006, 10:21 AM
  4. Quick question about SIGSEGV
    By Cikotic in forum C Programming
    Replies: 30
    Last Post: 07-01-2004, 07:48 PM
  5. pointer problem
    By DMaxJ in forum C Programming
    Replies: 4
    Last Post: 06-11-2003, 12:14 PM