Reputation: 31
I am trying to write recursive function which converts a binary numbers into decimal system. I couldn't find the bug. Any help will be appreciated deeply.
Here is my first attempt:
#include <iostream>
int sum = 0;
using namespace std;
int powerofO(int taban, int us)
{
int result = 1;
for (int i = 1; i <= us; i++)
result *= taban;
}
int func(int array[], int length, int weight);
int main()
{
int *size;
int digits;
int binary_array[*size];
cout << "how many digits ? \n";
cin >> digits;
*size = digits;
cout << "Enter your " << digits <<
" digits binary number using with a space between"
" each number \n";
for (int i = 0; i < digits; i++)
cin >> binary_array[i];
cout << func(binary_array, digits, -1) << endl;
return 0;
}
int func(int array[], int length, int weight)
{
if (length == 0) {
sum = sum + array[0];
return sum;
}
func(array, length - 1, weight + 1);
sum = sum + array[length] * powerofO(2, weight);
return sum;
}
And I tried to rearrange my function to the following, but it is still not working.
int func( int array[],int length ,int weight){
length--;
weight++;
if(length == 0){
sum = sum + array[0] * powerofO(2,weight);
return sum;}
sum = sum + array[length] * powerofO(2,weight);
func(array,length,weight);}
Upvotes: 2
Views: 3328
Reputation: 8637
In func() you are calling func() again before doing the sum. So then when length finally gets to 0, sum only contains the final digit in array[].
Upvotes: 0
Reputation: 104050
The cause of the immediate segmentation fault is very near the top of the main()
function:
int main()
{
int *size;
int digits;
int binary_array[*size];
int *size
only declares a pointer to an int, it does not actually allocate memory for that int. *size
is used a little later when trying to allocate the array, and the whole thing blows up.
So, a little re-arrangement and the program runs. I don't think the output is correct yet :) but I don't want to take away all your learning opportunities.
#include <iostream>
int sum = 0;
using namespace std;
int powerofO(int taban, int us)
{
int result = 1;
for (int i = 1; i <= us; i++)
result *= taban;
}
int func(int array[], int length, int weight);
int main()
{
int digits;
cout << "how many digits ? \n";
cin >> digits;
int binary_array[digits];
cout << "Enter your " << digits <<
" digits binary number using with a space between"
" each number \n";
for (int i = 0; i < digits; i++)
cin >> binary_array[i];
cout << func(binary_array, digits, -1) << endl;
return 0;
}
int func(int array[], int length, int weight)
{
if (length == 0) {
sum = sum + array[0];
return sum;
}
func(array, length - 1, weight + 1);
sum = sum + array[length] * powerofO(2, weight);
return sum;
}
Upvotes: 2