#1
  1. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2002
    Location
    Norway
    Posts
    0
    Rep Power
    0

    return addr of an struct-array


    Why doesn't this give the expected result:

    Code:
    /* start cpp-code */
    
    struct option
    {
        char *option2;
        char *value;
    };
    
    
    option *getOption(char *chrOption, int intMaxOption)
    {
    
        option *myOption;
        myOption = new option[intMaxOption];
    
        //code to fill myOption with elements
    
        return myOption;
    }
    
    
    int main(int argc, char* argv)
    {
    	
        option *myOption;
         char *test="opt1=222&opt2=333";
    
         myOption = getOption(test, 5);
    
        //all values in myOption gives the same as the 
        //last filled value in myOption.
        //ex. myOption[0].option2 will give the same as
        //myOption[2].value, even if they have different
        //values in the getOption function...
    
    		
         return 0;
    }
    
    /* end cpp-code */
    Yes, I know this could be done easier with classes in C++,
    but would like to have a solusion to this problem.

    -------
    Lars Andre
    http://www.itweb.no/
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    Oct 2000
    Location
    Back in the real world.
    Posts
    5,966
    Rep Power
    190
    //code to fill myOption with elements
    did you initialize option2 with new too on each run of your function? if not, it points to a random memory location, and you seem to have the same pointer each time, this is why you always get the last result which overwrote the one before..

    this can cause all kinds of weird effects anyway...

IMN logo majestic logo threadwatch logo seochat tools logo