The following program generates binary numbers of n numbers, with exactly k numbers "1". This does its job fine.
#include<stdio.h>
int n;
char arr[34] = {'\0'};
int sum = 0;
void TRY(int v) {
if (v == n) {
if (sum == 0) printf("%s\n", arr);
} else {
arr[v] = '0';
TRY(v 1);
if (sum > 0){
arr[v] = '1';
sum--;
TRY(v 1);
sum ;
}
}
}
int main() {
printf("Nhap k, n: ");
scanf("%d %d", &sum, &n);
TRY(0);
return 0;
}
However, if I replace line 8 with
if ((v==n) && (sum == 0)){
and delete the check sum == 0 on line 9, I get segmentation error. I just want to know why it is happening.
CodePudding user response:
You get a segmentation error because your code can't go below this line:
TRY(v 1);
Your base case
if ((v==n) && (sum == 0))
could never be true
unless sum
is already 0, if you assign anything to sum
other than 0, your base case will never be executed as it will never reach sum--
, as your base case doesn't get executed, v
will keep on incrementing, and at one point v
will become greater than the size of arr
and therefore causing a segmentation error.
CodePudding user response:
Oh, now I got it.
Your expectation is that the else branch will be run if and only if (v==n) && (sum == 0)
evaluates to false. That's wrong. It will execute if v==n
is false, regardless of sum
. So the check is not equivalent.
However, the printf("%s\n", arr);
will execute if and only if (v==n) && (sum == 0)
is false.
I'd recommend using this printf statements in a situation like this:
printf("sum: %d v: %d n: %d\n, sum, v, n);
And then like this:
void TRY(int v) {
puts("Entering TRY");
printf("sum: %d v: %d n: %d\n, sum, v, n);
if (v == n) {
puts("Entering if");
printf("sum: %d v: %d n: %d\n, sum, v, n);
if (sum == 0) printf("%s\n", arr);
} else {
puts("Entering else");
printf("sum: %d v: %d n: %d\n, sum, v, n);