Thread: Is it possible to return a string in a function?

  1. #1
    Registered User
    Join Date
    Apr 2007
    Posts
    2

    Is it possible to return a string in a function?


    Hello! I'm new to C and i have a very little understanding of C and i'm absolutely confused about strings and functions since i've been taught Java first.
    In java, you can make a method return a string, but:

    It is possible to make a function in C return a string?
    If so, what is the return type? Would it look like:

    eg.
    Code:
     char  nameoffuction()               since type string doesn't exit in C
          {   char[15] word = "imsoconfused";
               ...more coding in between...
               return word;
           }
    can you return the string word? or would i have to use a pointer to that string?
    I know this is silly and your probably wondering why am i trying to do this in a function but is it possible?

  2. #2
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    You don't want to return a pointer to a local object, and you can't assign arrays. A better example would help, because to me it somewhat looks like you are trying to reinvent strcpy.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  3. #3
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    Java hides a lot of the behind-the-scenes stuff from you. Every object is really a pointer or a reference to the actual object. In C, you don't have objects (at least not in the traditional sense, although you can fake them with function pointers).

    All strings are in C are just arrays of chars with a trailing '\0' char. A string can also be represented by a pointer to the first char of such a sequence.

    As already mentioned, in C you can't return local arrays because they get destroyed. I believe you can do it in Java because Java arrays are actually objects. The array you would have in a Java function is actually a pointer to that array object (which is dynamically allocated).

    The way to allocate objects in Java is through the new keyword. In C, dynamic memory is allocated through the malloc() function. Also of importance, you have to manually deallocate all allocated memory in C. You do this with the free() function.

    An example of how to return a string from a function would be something like this:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    char *getString(void);
    
    int main(int argc, char *argv[])
    {
    	char *szString;
    	
    	printf("Enter a string: ");
    	fflush(stdout);
    	
    	szString = getString();
    	
    	if(szString != NULL)
    	{
    		printf("You entered: &#37;s\n",szString);
    		free(szString);
    	}
    	else puts("Error!");
    	
    	return 0;
    }
    
    char *getString(void)
    {
    	int len;
    	char *s;
    	size_t ssize = BUFSIZ*(sizeof(*s));
    	
    	s = (char *)malloc(ssize);
    	if(!s)
    	{
    		return NULL;
    	}
    	if(fgets(s,ssize,stdin))
    	{
    		len = strlen(s) - 1;
    		if(s[len] == '\n') /* *Corrected* Thanks to Mr. Sinkula for finding this error. :) */
    		{
    			s[len] = '\0';
    		}
    	}
    	return s;
    }
    Last edited by MacGyver; 04-28-2007 at 11:50 AM.

  4. #4
    Registered User
    Join Date
    Apr 2006
    Posts
    2,149
    Also, in general, it is good style to malloc() and free() in the same function. This makes it easier to keep track of what you allocate, so that you remember to deallocate it afterwards. Remember, in C you have to free all heap memory after you use it*.

    *technically you don't have to free it if the program is about to terminate, but it is good style to anyway.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

  5. #5
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    I agree. It's best to malloc() and free() in the same function, but if you're returning a string from a function, you have no choice but to deallocate it elsewhere.

    Even though any modern O/S is supposed to clean up all memory allocated by your program after your program terminates, I don't believe that is guarenteed to always happen. Again, most modern O/S's will indeed do it, but I believe it's good practice to manually free() all memory that your program specifically *alloc()s.

  6. #6
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    Quote Originally Posted by MacGyver View Post
    Code:
    	if(fgets(s,ssize,stdin))
    	{
    		len = strlen(s) - 1;
    		if(s[len] = '\n')
    		{
    			s[len] = '\0';
    		}
    	}
    You might want to edit that.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  7. #7
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    Apologies and thanks. Error fixed.

  8. #8
    Registered User
    Join Date
    Apr 2006
    Posts
    2,149
    Quote Originally Posted by MacGyver View Post
    I agree. It's best to malloc() and free() in the same function, but if you're returning a string from a function, you have no choice but to deallocate it elsewhere.
    I general I agree. Sometimes though, it is still possible to pass the result string as an argument, if it is possible to know the required buffer size before the function is called. Strcat() and fgets() are examples of this.

    Even though any modern O/S is supposed to clean up all memory allocated by your program after your program terminates, I don't believe that is guarenteed to always happen. Again, most modern O/S's will indeed do it, but I believe it's good practice to manually free() all memory that your program specifically *alloc()s.
    What about a terminal error? C does not have exceptions, and for many functions it is hard make them return error code. If a terminal error is encountered in a deeply nested function call, it can be worthwhile to simply close the program rather then create a complicated system of error codes that trickle down to main, deallocating along the way.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

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