简体   繁体   中英

CodeBlocks C++ Exception

I'm having problem with this code:

#include<iostream>
#include<vector>
#include<algorithm>
#include<math.h>

using namespace std;

long long addV(int i) {
    return pow(10,i);
}

int len;

void recurse(int n,long long &ways,int values[],int current=0,int p=0) {
    if(p>len) return;
    if(current>n) return;
    if(current ==n) {
        ways++;
        return;
    }
    int cv = n-current;
    cv/=values[p];

    for(int i=0;i<=cv;i++) {
    recurse(n,ways,values,current+values[p]*i,p+1);
    }
}


int main() {
    int n;
    cin>>n;
    long long ways=0;
    int values[] ={1,2,3};
    len = sizeof(values)/sizeof(int);
    recurse(n,ways,values);
    cout<<ways;
}

The exception comes from (cv/=values[p];) line. Of course the shitty CodeBlocks never shows what the exception is. I'm sure its something easy to fix.

if(p>len)return;

Indeed you've already accessed over boundary when p == len . You need to return once p >= len .

Because among your ending condition for the recursion is p > len which means that p will be in the range from zero to three (inclusive). And as you know, an array of three entries have the indexes range from zero to two.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM