程序给出SIGSIGV错误

时间:2015-10-22 07:54:31

标签: c++ arrays binary-search-tree

我写了以下C ++程序给了我

  

SIGSIGV非常大的输入错误。

基本上以下程序输出的数字小于数组中的当前数字。我使用BST和数组来实现。

#include <iostream>
using namespace std;

struct bst {
    long long int data;
    struct bst *right;
    struct bst *left;
};

struct bst *head=NULL;
//function to increment 
void increment(struct bst *node,long long int w[]) {
    if(node==NULL)
    return;
    w[node->data] += 1;
    increment(node->left,w);
    increment(node->right,w);
}

void insert(long long int data,long long int w[]){
    struct bst *node;
    struct bst *current;
    current=head;
    if(head==NULL) {
        node = new bst;
        node->data = data;
        node->right = NULL;
        node->left=NULL;
        head=node;
        }else {
        while(1) {
            if(data > current->data){
                if(current->right!=NULL)
                current=current->right;
                else {
                    node = new bst;
                    node->data = data;
                    node->right = NULL;
                    node->left=NULL;
                    current->right=node;
                    break;
                }
            }
            else{
                if(current->left!=NULL){
                    //if data is less than current number than incremet 1 in right sub tree of current node 
                    //and current node
                    w[current->data] +=1;
                    increment(current->right,w);
                    current=current->left;

                }
                else {
                    node = new bst;
                    node->data = data;
                    node->right = NULL;
                    node->left=NULL;
                    current->left=node;
                    //if data is less than current number than incremet 1 in right sub tree of current node 
                    //and current node
                    w[current->data] +=1;
                    increment(current->right,w);
                    break;
                }
            }

        }
    }
}

void deletenode(struct bst *node) {
    if(node == NULL)
    return;
    deletenode(node->left);
    deletenode(node->right);
    delete(node);
}


int main() {
    int t;
    cin>>t;
    while(t--) {
        long long int n;long long int counter=0;
        cin>>n;
        long long int a[n];
        //array to keep count of numbers which are less than index of w[i]
        long long int w[1000000]={0};
        for(long long int i=0;i<n;i++) {
            cin>>a[i];
            insert(a[i],w);
        }
        for(long long int i=0;i<n;i++) {
            cout<<w[a[i]]<<" ";
        }
        cout<<"n";
        //deleting BST
        deletenode(head);
        head=NULL;
    }
    return 0;
}

任何帮助表示感谢。

1 个答案:

答案 0 :(得分:0)

main中,这可能会导致问题 -

long long int w[1000000]={0};

你应该在堆上分配内存。你可以这样做 -

long long int *w=new long long int[1000000]
相关问题