char *fun ()

This is a discussion on char *fun () within the C Programming forums, part of the General Programming Boards category; Code: char *fun (void) { char str [30]; fgets (str, 30, stdin); return str; } Is this wrong? Isn't it ...

  1. #1
    Registered User PutoAmo's Avatar
    Join Date
    Mar 2002
    Posts
    72

    Question char *fun ()

    Code:
    char *fun (void)
    {
     char str [30];
    
     fgets (str, 30, stdin);
    
     return str;
    }
    Is this wrong?

    Isn't it possible to return a pointer to a local variable?

    I get a warning when compiling.

  2. #2
    Registered User
    Join Date
    Jan 2002
    Location
    Vancouver
    Posts
    2,220
    It is better to do:

    Code:
    int fun(char *str)
    {
     fgets(str,30,stdin);
     return 0;
    }
    saves memory, use it like this:
    Code:
    fun(string);
    once that command is done, string will be set to whatever was input.

  3. #3
    Registered User C_Coder's Avatar
    Join Date
    Oct 2001
    Posts
    523
    char str [30];
    local variables only exist in the function they are declared in, so str will cease to exist when your function exits. Therefore you are returning a pointer to nothing.
    What you need to do is declare str as static, this means it will remain in memory.
    Code:
    char *fun (void)
    {
     static char str [30];
    
     fgets (str, 30, stdin);
    
     return str;
    }
    Or do as Brian said.
    All spelling mistakes, syntatical errors and stupid comments are intentional.

  4. #4
    Registered User PutoAmo's Avatar
    Join Date
    Mar 2002
    Posts
    72

    Thumbs up

    Thank you, guys !

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. C++ ini file reader problems
    By guitarist809 in forum C++ Programming
    Replies: 7
    Last Post: 09-04-2008, 06:02 AM
  2. Sorting Linked Lists
    By DKING89 in forum C Programming
    Replies: 6
    Last Post: 04-09-2008, 07:36 AM
  3. code condensing
    By bcianfrocca in forum C++ Programming
    Replies: 4
    Last Post: 09-07-2005, 09:22 AM
  4. Passing structures... I can't get it right.
    By j0hnb in forum C Programming
    Replies: 6
    Last Post: 01-26-2003, 10:55 AM
  5. String sorthing, file opening and saving.
    By j0hnb in forum C Programming
    Replies: 9
    Last Post: 01-23-2003, 12:18 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21