Thread: Problem with Pointer as return Argument

  1. #1
    Registered User
    Join Date
    May 2009
    Posts
    2

    Problem with Pointer as return Argument

    Hello, I am new to this place. Could you help me wit the following problem. Well the Pointer I trie to print in main doesn't show the content I have in the txt-File. I think I would feel better if I had an Array of Numbers instead of Chars after reading in the txt-File which only contains numbers, seperated with a "space bar".
    Code:
    int main(){
    
        //einige Standard-Variablen
        int i = 0;
        int j = 0;
        int z = 4;
    
    	//here I want to pass the Pointer from the Funktion to to another Pointer in Main
    	char * pSpielstaerken;
    	pSpielstaerken = einlesen();
            //THIS IS THE PROOF, THAT IT DOESN'T WORK
            while( pSpielstaerken[i] != '\0' ){
               printf( "%i ", pSpielstaerken[i] );
               i++;
            }   
    }
    
    //this is the Function to Read in a txt-File, pass it to a Char-Array in order to return it finally to the main Function
    char * einlesen(){
        FILE * input2;
        char charPuffer[50];
        char * pCharpuffer;
        pCharpuffer = &charPuffer[0];
        input2 = fopen("input2.txt","r");
        if (input2==NULL){
                         printf ("Fehler beim Einlesen");
                         }
    
        else {
             fgets (charPuffer, 50, input2);
             fclose (input2);
             }
    
        int i = 0;
    return (pCharpuffer);
    }

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    You are returning a pointer to an array that is local to the function which is returning it. That means that the space used by the array is free to be reused when the function has returned - there is no longer any memory for the array!

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  3. #3
    Registered User
    Join Date
    May 2009
    Posts
    2
    It works now, thank you very much.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How can I make this code more elegant?
    By ejohns85 in forum C++ Programming
    Replies: 3
    Last Post: 04-02-2009, 08:55 AM
  2. New string functions
    By Elysia in forum C Programming
    Replies: 11
    Last Post: 03-28-2009, 05:03 AM
  3. Replies: 2
    Last Post: 04-11-2008, 02:42 AM
  4. Replies: 8
    Last Post: 03-10-2008, 11:57 AM
  5. 6 measly errors
    By beene in forum Game Programming
    Replies: 11
    Last Post: 11-14-2006, 11:06 AM