Thread: question about c functions

  1. #1
    Registered User
    Join Date
    Nov 2005
    Posts
    19

    question about c functions

    Hi all, I've got a little question about functions in c, I wrote a whole "program" (well, not so big, but still), which I am not going to post here, it's not important, instead I will try to explain my problem with a little example

    assume you've got this:

    Code:
    int number = 4;           //length of word string
    char word[number];       //declaration of word
    
    //later in the program, you specify the value f.e.
    
    //here comes input code for first char
    word[0] = 'f'
    //here comes input code for second char
    word[1] = 'o'
    //...
    word[2] = 'o'
    //...
    word[3] = '\0'
    now, in my program, the input is done by the user, character by character (it's on my psp)
    my question is, can I put the whole thing into a function, which first asks the user to input char by char, and then returns the whole string
    the point is being able to put the function into a header file, so I can keep my code clean

  2. #2
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    I think the problem you're running into is returning the address of a local variable. You can't do something like:
    Code:
    char *func(void)
    {
      char word[] = "foo";
    
      return word;
    }
    For the exact same reason you can't do this:
    Code:
    int *func(void)
    {
      int a;
    
      return &a;
    }
    Local variables in a function are created on the stack and as soon as that function returns the stack space allocated for that function becomes invalid.

    A few solutions:
    - Declare word as static (e.g. static char word[] = "foo" This changes the lifetime of word from until-the-function-returns to until-the-program-ends.
    - Pass word in from the calling function instead of declaring it within the function.
    - Use dynamic memory allocation to get the memory for word. The calling function will need to free() the memory when it's done with it.
    - Declare word as a global variable.
    If you understand what you're doing, you're not learning anything.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Beginner's question about functions.
    By Crocodile23 in forum C Programming
    Replies: 4
    Last Post: 01-13-2009, 07:00 AM
  2. Functions Question
    By audinue in forum C Programming
    Replies: 2
    Last Post: 01-09-2009, 09:39 AM
  3. functions question.
    By Boozel in forum C Programming
    Replies: 1
    Last Post: 02-23-2008, 12:38 AM
  4. Question concerning functions
    By Warrax in forum C++ Programming
    Replies: 5
    Last Post: 04-04-2007, 11:00 AM
  5. Question about creating flash functions
    By jbh in forum C++ Programming
    Replies: 8
    Last Post: 11-21-2005, 09:39 AM