Hello,
I am making this TSP solver using a genetic algorithm. And I ran into this problem and I can't work it out. The problem is, I pass the two parent genes and the two child genes into the crossover function and then the crossover function is supposed to allocate memory for the child genes and fill them accordingly. But after the function has finished, the two child genes are NULL. I debugged and found out that inside the crossover function they are allocated separate memory and are filled out accordingly. But when the function returns, they become NULL. I am using a static function. Is this in someway to be blamed? But I tried changing it into a regular member function and still the same problem occurs. I' d be very glad if anyone can help. I am providing the relevant code below. Thanks.
I am making this TSP solver using a genetic algorithm. And I ran into this problem and I can't work it out. The problem is, I pass the two parent genes and the two child genes into the crossover function and then the crossover function is supposed to allocate memory for the child genes and fill them accordingly. But after the function has finished, the two child genes are NULL. I debugged and found out that inside the crossover function they are allocated separate memory and are filled out accordingly. But when the function returns, they become NULL. I am using a static function. Is this in someway to be blamed? But I tried changing it into a regular member function and still the same problem occurs. I' d be very glad if anyone can help. I am providing the relevant code below. Thanks.
Code:
static void Crossover(CGene & parent1, CGene & parent2, CGene * child1, CGene * child2) { child1 = new CGene(parent1); child2 = new CGene(parent2); double doCrossover = Random((double)0.0f, (double)CROSSOVER_RATE); //Perform crossover CROSSOVER_RATE% of the time if(doCrossover < CROSSOVER_RATE) { //Partially Matched Crossover //-------------------------------------------------------------------- int low, high; //Two crossover points low = Random(0, GENE_LENGTH); high = Random(0, GENE_LENGTH); if(low > high) { int temp = low; low = high; high = temp; } int * temp = new int[high - low]; //Actual crossover in the range [low, high) for(int i = low; i < high; i++) { temp[i - low] = child1->gene[i]; } for(i = low; i < high; i++) { child1->gene[i] = child2->gene[i]; } for(i = low; i < high; i++) { child2->gene[i] = temp[i - low]; } //Perform the rehabilitation here } }
Code:
CGene(const CGene & gene) { this->gene = new int[GENE_LENGTH]; for(int i = 0; i < GENE_LENGTH; i++) { this->gene[i] = gene.gene[i]; } this->fitness = gene.fitness; this->cost = gene.cost; }
Comment