Results 1 to 2 of 2

Thread: return string from function

  1. #1

    Thread Starter
    Frenzied Member CyberCarsten's Avatar
    Join Date
    Sep 1999
    Location
    Aalborg Ø, Denmark
    Posts
    1,544

    return string from function

    Hi
    I have a small fileloading function. The function loads a file passed on to it by a filechooserdlg, within that file, is the name of another file to load....but I don't know how to return it......
    Here it is:
    Code:
    #include "defines.h"
    
    char *loadmap(char *map) {
      FILE *file;                       // pointer to FILE structure
      char str[STR_LEN];            // String for holding file content
      int ch;                           // Check for EOF
      int i = 0;                        // Loop counter var
      
      file = fopen(map,"r");    // Open file
    
    
      while ((ch = fgetc(file)) != EOF){ // Store the content in str
        str[i] = ch;
        i++;
      }
      str[i] = '\0';
    
      
      fclose(file);                          // Cleanup  
    
      return str;                           // Returned filename - - not working
    }
    I am calling the loadmap function like this:
    Code:
     char *filename;
    
        filename = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (dialog));
    char *map;
        map= loadmap(filename);
    Can anyone see the error???
    razor
    Software Engineer Student, Aalborg University, Denmark
    http://www.cs.auc.dk

    My email at AUC: will get a new email soon
    My website: http://www.razorsoftware.net


    Windows XP Pro/ Gentoo Linux (Laptop)
    Windows XP Pro (Home PC)

  2. #2
    Frenzied Member aewarnick's Avatar
    Join Date
    Dec 2002
    Posts
    1,037

    Re: return string from function

    str is a local variable. It is destroyed after the function returns.

    You need to either make str static or dynamically allocate memory and return the pointer, just remember to delete[] it.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width