简体   繁体   中英

Array of Nodes: Initialization

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

using namespace std;

struct Node{
    string data;
    Node* next;
    Node(){
        data = "";
        next = NULL;    
    }       
};

int computeHash(string s, int m){
    int p = 1000000007;
    int x = 263;
    unsigned long long sum = 0;
    unsigned long long val = 0;
    for(int i = 0; i < s.length(); i++){
        val = pow(x, i);
        sum = (sum + s[i] * val) % p;   
    }
    sum = sum % m;
    return sum;
}

int main(){
    int buckets;
    cin >> buckets;
    int n;
    cin >> n;
    string tag;
    string s;
    vector< vector<string> > myStore(n);
    for(int i = 0; i < n; i++){
        cin >> s;
        myStore.at(i).push_back(s);
        cin >> tag;
        myStore.at(i).push_back(tag);   
    }
    Node** arr= new Node*[buckets];
    for(int i = 0; i < n; i++){
        if(!myStore[i][0].compare("add")){
            s = myStore[i][1];
            int hash = computeHash(s,buckets);
            cout << hash << endl;
        }

    }

    return 0;   
}

I am trying to write a program to implement hashing with chains. I am trying to create an array of nodes so that I can append if two strings have the same hash value.

But I am having a problem with the initialization of array of Nodes. I thought the nodes in the array would be pointing to NULL. But when I tried to debug in gdb it is showing some other thing. 在此处输入图片说明

Can someone explain where I am wrong on comment about this behavior. Why arr 1 and arr[2] are pointing to some memory location instead of null. I also tried to remove the default constructor but still getting the same results. Any help would be appreciated.

You're allocating an array of pointers. Pointers don't have constructors, or default initialization; you're getting random memory (from the allocation).

If you want the array to be NULL-ed out, you need to do so yourself (eg: memcpy, etc.).

You have initialized vector of size n of vectors of size 0 of strings. Then you want to get the '[1]' (the second element of empty vector of strings) You have to inutialize them separately. eg in "for" cycle.

Updated. Use myStore.at(i).at(1) instead of myStore[i][1] to achieve checking of boundary conditions. (Try it, you will understand that the problem with vector indeed)

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