Stack Overflow Asked on January 29, 2021
A recursive code to find power set of string is showing error and out of memory.
void recur(string a,string b,int i=0) // Recursive fun
{
int n=a.size();
if(i==n) //returns if becomes equal to the size of array
{
cout<<b<<endl;
return ;
}
recur(a,b,i++); //calls without append
recur(a,b+a[i],i++); //calls with append
}
i++
doesn't do what you want it to do in this context, it increments the variable i
and returns the value before the increment. For example
int i = 0;
cout << i++; // prints 0
cout << i; // prints 1
You could use pre-increment like ++i
, which evaluates to the value after the increment.
Also for recur(a, b + a[i], ++i);
, the evaluation order of the parameters is unspecified, so the value of a[i]
is unspecified. I suggest not using increment operators at all in this case, as it just makes the code harder to read.
Answered by IlCapitano on January 29, 2021
If you call the function as recur(a,b);
then in this line
recur(a,b,i++); //calls without append
i
is still 0
. That line will call the function again with exact same parameters and you get a stackoverflow due to infininte recursion.
Answered by largest_prime_is_463035818 on January 29, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP