How to safely return int pointer

I have a lookup function in my hash table class which returns a pointer to the hash table bucket if the element x is found. Is this a safe way to declare a pointer and return it?

1
2
3
4
5
6
7
8
9
10
11
12
int * hashtable::lookup(double x) {
	int bucket = hash(x);    //hash(x) returns an int.
	int *BukPtr = new int;
	BukPtr = &bucket;
	linkedlist *LL = &hash_table[bucket];

	if(LL->search(x)) {
		return BukPtr;
	}
	else
		return 0;
}
No.
 
*BukPtr = bucket;

It'd be better to only allocate and assign after the call to LL->search() has returned true.
ok so

1
2
3
4
5
6
7
8
9
10
11
12
int * hashtable::lookup(double x) {
	int bucket = hash(x);    //hash(x) returns an int.

	linkedlist *LL = &hash_table[bucket];

	if(LL->search(x)) {
                int *BukPtr = bucket;
		return BukPtr;
	}
	else
		return 0;
}


So int *BukPtr = bucket; allocates and assigns all in one step?
Not quite; you are misusing helios's statement. You want:
1
2
3
int* BukPtr = new int; // make space
*BukPtr = bucket; // put value in that space
return BukPtr; // return address of the space you created 
No.

1
2
int *BukPtr = new int;
*BukPtr = bucket;
or
 
int *BukPtr = new int(bucket);
or
 
return new int(bucket);
Last edited on
Topic archived. No new replies allowed.