Thread: returning a string from a function

  1. #1
    Registered User
    Join Date
    Apr 2009
    Posts
    74

    returning a string from a function

    is anything wrong with this approach?

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    void str_output(char *x) 
    {
    	scanf("%s", x);
    	
    	/*
    		do something with the string...
    	*/
    }
    
    int main(int argc, char *argv[])
    {
    	char s[20];
      
    	printf("Input string: ");
    	str_output(s);
      
    
    	/*
    		do something with the string...
    	*/
    
      return 0;
    }
    it seems to work but I keep looking around and waiting for something to hit me in the head

  2. #2
    Jack of many languages Dino's Avatar
    Join Date
    Nov 2007
    Location
    Chappell Hill, Texas
    Posts
    2,332
    Type in a string longer than 19 characters (no spaces) and see what happens.
    Mainframe assembler programmer by trade. C coder when I can.

  3. #3
    Registered User
    Join Date
    Apr 2009
    Posts
    74
    Of course, but apart from that, if the user ALWAYS enters less than 20 characters, is it ok?

  4. #4
    Jack of many languages Dino's Avatar
    Join Date
    Nov 2007
    Location
    Chappell Hill, Texas
    Posts
    2,332
    Seems fine to me.
    Mainframe assembler programmer by trade. C coder when I can.

  5. #5
    and the hat of sweating
    Join Date
    Aug 2007
    Location
    Toronto, ON
    Posts
    3,545
    Users always do stupid things, and you need to make your program handle those things.
    You should also pass a size parameter to the str_output() function that indicates the size of the string you're passing to it and only enter up to size - 1 characters.
    "I am probably the laziest programmer on the planet, a fact with which anyone who has ever seen my code will agree." - esbo, 11/15/2008

    "the internet is a scary place to be thats why i dont use it much." - billet, 03/17/2010

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Compiling C in Visual Studio 2005
    By emanresu in forum C Programming
    Replies: 3
    Last Post: 11-16-2009, 04:25 AM
  2. Getting an error with OpenGL: collect2: ld returned 1 exit status
    By Lorgon Jortle in forum C++ Programming
    Replies: 6
    Last Post: 05-08-2009, 08:18 PM
  3. OOP Question DB Access Wrapper Classes
    By digioz in forum C# Programming
    Replies: 2
    Last Post: 09-07-2008, 04:30 PM
  4. We Got _DEBUG Errors
    By Tonto in forum Windows Programming
    Replies: 5
    Last Post: 12-22-2006, 05:45 PM
  5. returning a string from a function
    By itld in forum Linux Programming
    Replies: 5
    Last Post: 12-03-2001, 01:35 AM