Thread: A function to return a string

  1. #1
    Registered User
    Join Date
    May 2005
    Location
    Toronto, Canada
    Posts
    257

    A function to return a string

    Hey,

    I was wandering how to make a function return a string. I know it's easier with C++, but I have to work in C.

    I've looked through the threads here and the FAQ and not much usefullness came back.

    I'm trying to make a function that will read from a file a word at a time and leave the pointer at the end of the word. If the input file is like so:
    Code:
    May June July
    After the file has been opened, I want the function at first call to go get May, and copy it into an array of char. I did it like so:
    Code:
    char GetWord(FILE *inp)
    {
    	int i=0;
    	char string[50];
    
    	while (string[i]!= '\"' && string[i]!= EOF)
    	{
    		 string[i] = fgetc ( inp );
    		 printf("%c ", string[i]);
    		 i++;
    	}
    
    	return string;
    }
    and to call it:
    Code:
    char Word[25];
    
    Word = GetWord(inp);
    It is all kinds of wrond. I'm not really sure if I can do this.

  2. #2
    Registered User
    Join Date
    Sep 2001
    Posts
    4,912
    Return a pointer.

    Code:
    char *function(type parameter)
    {
        char *value = "string";
        return value;
    }

  3. #3
    Anti-Poster
    Join Date
    Feb 2002
    Posts
    1,401
    You're returning a pointer to a local variable...not a good thing. Try something like this:
    Code:
    bool GetWord(FILE *inp, char *string)
    {
    // code
    // return false if read error, true otherwise
    }
    If I did your homework for you, then you might pass your class without learning how to write a program like this. Then you might graduate and get your degree without learning how to write a program like this. You might become a professional programmer without knowing how to write a program like this. Someday you might work on a project with me without knowing how to write a program like this. Then I would have to do you serious bodily harm. - Jack Klein

  4. #4
    The C-er
    Join Date
    Mar 2004
    Posts
    192
    The blind leading the blind....

    Advice from the one eyed King -

    @Earth angel. - you need to make your string declaration static like so

    Code:
    static char string[50];
    Otherwise once the functions completes, the string is no longer allocated and thus it's pointer is invalid. Sean's code is correct only because he's returning a pointer to a constant string. It won't work for variables.

    Also when you enter your while loop for the first time, you're testing it before it's been initialised. Either initialise it first, or perhaps use a do..while loop.

  5. #5
    Registered User
    Join Date
    May 2005
    Location
    Toronto, Canada
    Posts
    257
    This works:
    Code:
    int GetWord(FILE *inp, char *string)
    {
    	int i=0;
    
    	printf("\n\n==================================");
    	printf("\nFunction output\n");
    
    	while (string[i]!= '\"' && string[i]!= EOF)
    	{
    		 string[i] = fgetc ( inp );
    		 printf("%c ", string[i]);
    		 i++;
    	}
    
    	if (string[i] == NULL)
    		return 0;
    	else
    		return 1;
    
    }
    and the call:

    Code:
    check = GetWord(inp, Word);
    
    	
    
    	if (check)
    		printf("\n\n*   %s\n\n", Word);
    But the loop control is off. I'm looking for the first white space with \", but it goes on past it, until it feels like stopping.

    ie: input file:
    Code:
    May June July August
    Setember October
    the function stores this in Word:
    Code:
    May June July August
    Setember
    Last edited by earth_angel; 06-09-2005 at 01:02 PM. Reason: Misspelling

  6. #6
    Registered User
    Join Date
    May 2005
    Location
    Toronto, Canada
    Posts
    257
    Quote Originally Posted by Jez
    Code:
    static char string[50];
    Otherwise once the functions completes, the string is no longer allocated and thus it's pointer is invalid. Sean's code is correct only because he's returning a pointer to a constant string. It won't work for variables.
    I know I can't return a pointer to a local variable, but having a sting[50] constant doesn't help. Or at least I don't know how to make it helpful. I can't return a string. .....Unless I'm not understanding your advice correctly.

  7. #7
    Registered User
    Join Date
    Jan 2005
    Posts
    184
    try out this bit of code which migght help u
    Code:
    #include<stdio.h>
    
    char * change()
    {
        static char array[10]={"hello"};
        return array;
    }
        
    int main()
    {
        char *arr=malloc(10);
        
        arr=change();
        
        printf("%s",arr);
        
        getchar();
    }
    NOTE: static string in the function

    -s.s.harish

  8. #8
    Registered User
    Join Date
    May 2005
    Location
    Toronto, Canada
    Posts
    257
    The function to return an array is ok now. The only thing is that the loop won't get out when it hits white space in the file.

    Can I not compare
    Code:
     string[i]!='\" '
    ? from
    Code:
    int GetWord(FILE *inp, char *string)
    {
    	int i=0;
    
    	printf("\n\n==================================");
    	printf("\nFunction output\n");
    
    	do
    	{
    		 string[i] = fgetc ( inp );
    		 printf("%c ", string[i]);
    		 i++;
    	}
    	while (string[i]!= '_' && string[i]!= (char)EOF);

  9. #9
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    ie: input file:

    Code:
    May June July August
    Setember October
    I don't see a quote (") in your input file. Are you looking for spaces, quotes, or both?

  10. #10
    Anti-Poster
    Join Date
    Feb 2002
    Posts
    1,401
    Quote Originally Posted by Jez
    The blind leading the blind....

    Quote Originally Posted by earth_angel
    The only thing is that the loop won't get out when it hits white space in the file.
    Well, since you're checking for quotations, that's no surprise. If you want to break on spaces only, you can compare against ' '. However, if you want to break on all whitespace (tabs, newlines, etc.), you can use isspace().

    Something you may want to add is a buffer length to your function; you don't want to be running off the end of your buffer. Consider the difference between gets, fgets, and why one is considered better than the other.
    If I did your homework for you, then you might pass your class without learning how to write a program like this. Then you might graduate and get your degree without learning how to write a program like this. You might become a professional programmer without knowing how to write a program like this. Someday you might work on a project with me without knowing how to write a program like this. Then I would have to do you serious bodily harm. - Jack Klein

  11. #11
    The C-er
    Join Date
    Mar 2004
    Posts
    192
    >but having a sting[50] constant doesn't help. Or at least I don't know how to make it helpful.

    string[50] is a variable , not a constant, so it needs to be declared static if you want to return a pointer to it.

    Perhaps I didn't word it well, but what I was trying to say is that Mr Mackrory's post is unhelpful for your requirements (although correct).


    >I can't return a string. .....Unless I'm not understanding your advice correctly.

    You can return a pointer to a string array, but like I say you need to declare it static in your function.

    Also why are you using \" ? This just searches until it finds the " character. If you're looking for whitespace then just use ' ' (theres a space between those quotes BTW).

    In your "working" example you're still testing your string before it's been initialised. This means it could fail unexpectedly. Really you should be testing the character that you read from the file before assigning it to your array.

  12. #12
    Registered User
    Join Date
    Jan 2005
    Posts
    184
    Code:
    while (string[i]!= '_' && string[i]!= (char)EOF);
    what is this?. if u are looking for a '\' then this is not the proper statment to check

    Code:
    while(string[i]!='\'   . . . . . )
    - s. s. harish

  13. #13
    Registered User
    Join Date
    Jan 2002
    Location
    Vancouver
    Posts
    2,212
    Code:
    char *function(void)
    {
        char *s = malloc(sizeof(char) * 6);
        strcpy(s, "hello");
        return s;
    }
    
    int main(void)
    {
        char *s = function();
        printf("%s", s);
        free(s);
    }

  14. #14
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    You mean other than the fact that you don't check to see if malloc actually fails or not? Also, sizeof( char ) is always 1.


    Quzah.
    Hope is the first step on the road to disappointment.

  15. #15
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Quote Originally Posted by ssharish
    try out this bit of code which migght help u
    Code:
    #include<stdio.h>
    
    char * change()
    {
        static char array[10]={"hello"};
        return array;
    }
        
    int main()
    {
        char *arr=malloc(10);
        
        arr=change();
        
        printf("%s",arr);
        
        getchar();
    }
    NOTE: static string in the function

    -s.s.harish
    Once again, your code is horribly wrong. You create a memory leak here:
    Code:
        char *arr=malloc(10);
        
        arr=change(); /* What happened to what you malloced? */
    You're also wrong here:
    Code:
    char GetWord(FILE *inp)
    {
    	int i=0;
    	char string[50];
    
    	while (string[i]!= '\"' && string[i]!= EOF)
    what is this?. if u are looking for a '\' then this is not the proper statment to check
    Code:
    while(string[i]!='\'   . . . . . )
    You're wrong for two reasons:

    1) They were looking for quotation mark: ". The correct way to find the character " is to escape it. They did that correctly. This is correct:
    Code:
    string[i]!= '\"'
    The rest of that line is what's wrong:
    Code:
    && string[i]!= EOF)
    A char can NEVER contain the EOF marker. Therefore, never test a char to see if it is in fact EOF. It can never happen. Also, typecasting EOF to a char breaks what EOF is. Never typecast EOF. Ever.

    2) The second reason you're wrong, is because if you're trying to find the backslash character ( \ ) then you do not do what you have illustrated:
    Code:
    while(string[i]!='\'   . . . . . )
    Even if you removed the "....." portion, this code wouldn't even compile. You have to escape the backslash character, just like you have to escape quotes. Didn't you learn this? This is like one of the first things you learn when dealing with characters and strings. If they did in fact want a backslash, this is how you would do it:
    Code:
    while( string[ i ] != '\\' )
    Yes. It is like the blind leading the blind. *chuckle*


    Quzah.
    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Compiling sample DarkGDK Program
    By Phyxashun in forum Game Programming
    Replies: 6
    Last Post: 01-27-2009, 03:07 AM
  2. In over my head
    By Shelnutt2 in forum C Programming
    Replies: 1
    Last Post: 07-08-2008, 06:54 PM
  3. Replies: 8
    Last Post: 04-25-2008, 02:45 PM
  4. Inheritance Hierarchy for a Package class
    By twickre in forum C++ Programming
    Replies: 7
    Last Post: 12-08-2007, 04:13 PM
  5. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM