Thread: Help with returning an array

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Jan 2009
    Posts
    1,485
    Quote Originally Posted by vart View Post
    this does not fixes the main problem - you cannot return pointer to local var.
    But in this case the return value is assigned to a local variable in main. Wouldn't that solve the problem, like this?

    Code:
    #include <stdio.h>
    char *st();
    
    int main()
    {
            char *s = st();
            puts(s);
            puts(st());
    
            return 0;
    }
    char *st(){
            char *s = "There!";
            return s;
    }

  2. #2
    Registered User
    Join Date
    Jan 2009
    Location
    Australia
    Posts
    375
    No, in that example you are returning a pointer to a string literal. The string literal is in read only memory and will not be overwritten by anything.

    In your previous example you are returning a pointer to a local variable. This could be overwritten on other adjacent function calls and is probably undefined or implementation specific.

    As vart said, you should use malloc to create your array on the heap or you can supply the function with the variable and fill it then.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Parsing and returning array pointers?
    By thealmightyone in forum C Programming
    Replies: 26
    Last Post: 03-26-2009, 03:38 PM
  2. Returning an Array
    By mmarab in forum C Programming
    Replies: 10
    Last Post: 07-19-2007, 07:05 AM
  3. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM
  4. Replies: 6
    Last Post: 10-21-2003, 09:57 PM
  5. Help with an Array
    By omalleys in forum C Programming
    Replies: 1
    Last Post: 07-01-2002, 08:31 AM