Recursive binary search - C++ [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
first post here so be gentle. I'm trying execute a recursive binary search. I have tried different variations of code to try to make the function work but i still doesnt.
Here's my code:
bool contained(int x, const int* pBegin, const int* pEnd){
if(x==*pBegin) { //
return pBegin;
}
int size = pEnd - pBegin; //size of the array
int mid= size/2; //the middle of the array
int const* pMid = pBegin + mid; //The address of the element in the middle of the array
if(x>*pMid) //Condition that looks if x is to the left of the array
return contained(x,pMid,pEnd);
else if(x<*pMid) //Condition that looks if x is to the right of the array
return contained(x,pBegin,pMid-1);
}
int main()
{
cout << "Binary search, test: " << endl;
int arr[] = {1,2,3,4,5,7,8,9};
int size = 9;
for(int i=0; i<size; i+=1)
arr[i] = i;
bool find = containedInSortedarray(6, &arr[0], &arr[size]);
cout << "Found " << find << endl;
}
For example here, when i execute my bool-contained function with a premade array and let it search for the value 6, it should eventually come to the conclusion that the element does not exist, yet my output says it does. Have i missed something in my code?
Thanks in advance!

There are a couple of issues with your code:
You never return false.
You return pBegin which is not a bool, (sadly in your case) it is implicitly convertible to one, but not in the way you want it too. Turn on your compiler warnings all the way up - -Wextra -Wall -pedantic -Werror should be the bare minimum, especially if you are a beginner.
Be precise about the interval your function searches in. func(x,a,b) - does it include b? Based on contained(x,pBegin,pMid-1); it seems it does, but in the case of containedInSortedarray(6, &arr[0], &arr[size]); hopefully not.
Dereferencing &arr[size] is UB.
What is the purpose of the for loop in main?
Having the size detached from the array is a disaster waiting to happen. At least use sizeof(arr)/sizeof(arr[0]). Better yet, use std::array or a std::vector.
I would suggest searching [a,b) because it can be easily be divided into [a,mid), [mid,end). That way your mid computation is already correct. You can then call it like containedInSortedarray(x,arr,arr+arr_size)
The base condition should catch the arrays of size 0 and 1 - both can be trivially tested for presence of x.

Related

c++ copy object to pointer array [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I have a pointer array of Word (objects) and I have to assign another object of type Word to this objects array.
Using this two lines of code I put the new object w inside my objects array (word).
Word w = Word(new_word, len);
this->word[index - 1] = w;
Then I print my objects array and everything comes out right
for (int k = 0; k < this->len; k++) {
cout << this->word[k].getChars() << endl;
} // End of function 1
After "End of function" we return to the main class that call to another function.
This function print the objects array again but now the function does not print the w object that I insert in the previous function.
Second function
for (int k = 0; k < this->len; k++) {
cout << this->word[k].getChars() << endl;
} // End of function 2
Can anyone explain to me why this is happening and how it can be arranged.
Though it's difficult to be certain (since we don't have the rest of the function to look at), it seems that you may have a dangling pointer issue.
When you declare Word w = Word(new_word, len); in your function, you're declaring it as a local variable, placing it on the stack. Adding this to the array doesn't cause any issues when you're still in the function, but once you return from where you came, the function's memory - including Word w - is destroyed. When you try to access that memory location again by printing it from the array, you're looking for a variable that no longer exists, and thus get undefined behavior.
Luckily, you're using c++, and heap memory management is fairly well supported! I would consider implementing word as an array of pointers. If you then try something like this...
Word *w = new Word(new_word, len); //use "new" to create an object on the heap - persistent after you leave the function!
this->word[index - 1] = w; //make sure this->word is now an array of Word*; it seems to currently be an array of Word
...you may find the problem solved. Just don't forget to free it when you're done!

Crashing Pointer Array C++ [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
Code::Blocks, Win7, C++
Hi, I'm creating an overview project for myself, and an integral part includes doing an Exchange Sort in descending order. I've created a simple trial run to test the concept.
Embarrassingly enough, I can't get past creating the array without the project crashing. This only happens when I create the array with pointers (My project's arrays are pointers, which is why I need this to work). The code compiles fine, but when I run it, I get a Window's notification that "ArrayTest.exe has stopped working"
When I print out each dereferenced value, I get:
"The original order: 1 13 5 7 2 "
When I print out each value's address, I get:
"The original order: 0x28ff08 0x28ffc4 0x760c8cd5 0x6aadab61 0xfffffffe "
The last address showed up when using an array length of 6, and crashes as well. Am I blind to a simple error in my code, or is this a hardware issue?
//filename ArrayTest
#include <iostream>
using namespace std;
int main()
{
int *j[5];
(*j)[0] = 1;
(*j)[1] = 13;
(*j)[2] = 5;
(*j)[3] = 7;
(*j)[4] = 2;
cout << "The original order: ";
for (int i = 0; i < 5; i++)
{
cout << (*j)[i] << " ";
}
return 0;
}
Consider int *j[5]; carefully. This is an array of pointers.
Those pointers are not pointing to memory that you own.
So the behaviour on dereferencing them is undefined.
Trivial fix: use int j[5]; instead, and j[0] = 1 etc.
When analysing code problems consider these numbers as approximating the probability of the error location:
99.0% - your code
0.9% - the standard library
0.09% - the compiler
0.009% - the operating system
0.001% - the hardware
If you want a pointer on array, you have to use this syntax
int array[5];
int (*j)[5] = &array;
(*j)[0] = 42;
So, firstly, the correct syntax is int j[5]; but that's C, not C++.
use std::array - actual C++ and with compile-time checking.
You're allocating an array of 5 pointers to int, not an array of 5 integers. Try to init the array like this: int j[5];
Your code writes your values 1, 13, 5, 7, 2 to the dereferenced pointers in your pointer array. Since they are uninitialized, they contain garbage and thus you're writing to random addresses in memory, which leads to the crash.

whats wrong with my code for arrays [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
i am trying to generate an array which may be independant of dimensions. i tried doing this
#include <iostream>
using namespace std;
class array3d
{
public:
array3d(size_t* d, int dims)
{
int all = 1;
size_t* dimensions;
int* array;
for (size_t i = 0; i < dims; i++) {
all = d[i];
dimensions = new size_t[dims];
array = new int[all];
std::cout << array[i] << std::endl;
}
}
};
int main()
{
size_t d[6];
d[0] = 2;
d[1] = 3;
d[2] = 4;
d[3] = 2;
d[4] = 3;
d[5] = 4;
array3d arr(d, 6);
return 0;
}
when i compile it i end up with an array of zeros alone, i am not able to find where i going wrong. can anyone help?
I cannot really understand the logic behind you code, but if you simply want to see something printed you probably meant to do this:
array = new int [all];
//write something here first!
array[i] = some_value; <--- Note that this may access past the end of the array
std::cout << array[i] << std::endl;
Or more likely you wanted this:
std::cout << d[i] << std::endl;
Note1: You should really listen to 0d0a and use std::vector unless you really need arrays
Note2: You're doing some signed to unsigned comparisons (i < dims) - you might want to take care of those too
array = new int[all]; does not initialize the allocated memory. It will just make the allocation from heap, but leave the contents of memory as it was (or, actually, accessing the allocated but uninitialized memory may be Undefined Behaviour, strictly speaking).
You see zeros only by chance, because the memory happens to contain zeros. It is zeros probably because it has not been allocated, used and released by your program yet, and OS filled it with zeros before giving it to your program.
Additionally, std::cout << array[i] << std::endl; will be buffer overflow, if i>=all. Why do you do that anyway?
And finally, your code leaks memory like crazy. Your loop loops dims times, and with each iteration you do two allocations with new, but then you lose the returned pointers.
In short, use std::vector in C++, (almost) never use plain C arrays. If you have a clear use case for a fixed length array, use std::array. Furthermore, most of the time, if you are using naked pointers in C++ application code, you are not doing it right. Use smart pointers. This applies especially, if you are learning C++ today. Learn the modern way of doing things, it will make your life so much easier, while improving quality of your code.

Getting Array from Another class C++ [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I am making a simple Lottery program - and am struggling with implementation. I have a class called 'Ticket Line' this class simply holds 6 numbers that the player is playing a lottery for.
What I want to do, is generate 6 randomly (got function for this already) and then store that in another class as values. To do this, I am using the following code:
class Draw
{
private:
int drawID;
TicketLine* DrawnNumbers;
bool drawn;
}
When a Draw is completed I want to generate the Random Numbers ( from the TicketLine class) and then for the Draw to be able to store those numbers into its Draw File.
How would I be able to access the functionality of the DrawnNumbers class - and store the results from the getTicketNumbers.getTicketLine()function.
int* getTicketNumbers(void) { return DrawnNumbers->getTicketLine();};
The program crashes the following code:
//int *ptr[6] = getTicketNumbers();
int *ptr[6] = getTicketNumbers();
for (int x = 0; x < 6; x++){
cout << ptr[x];
}
TicketLine class:
private:
int select[6]; //Array of Ticket Numbers.
int* getTicketLine(void) { return select; };
I am willing to offer a couple of virtual beers to the solution. I am as yet to find a good online pub - if you know of one then please do let me know :-)
Thanks,
Without knowing any more, this line:
int *ptr[6] = getTicketNumbers();
is very suspect.
Why? Well, we haven't seen the implementation of getTicketNumbers so we don't know if it's actually allocating memory for 6 and returning such an array.
Also, you are printing the values of pointers here:
for (int x = 0; x < 6; x++){
cout << ptr[x];
}
Where, if you intended to actually print the int values, you'd say something like this:
for (int x = 0; x < 6; x++){
cout << *(ptr[x]);
}
My guess is that you are either:
Going out of bounds of an array that was (not) allocated, or,
Modifying actual pointer values somewhere instead of the integers they point to (as indicated by your lack of dereferencing ptr[x] in your print statement)
Edit
With more information, it seems you probably meant to say this:
int *ptr = getTicketNumbers();
instead of this:
int *ptr[6] = getTicketNumbers();
You should probably be doing some sanity checks as well to make sure that select is actually filled before calling that function (maybe giving it a default value of {0,0,0,0,0,0} in the constructor)
DrawnNumbers doesn't appear to be pointing to anything yet. It's a pointer, but to what?
Also, be careful about returning arrays that way. If the object or stack frame that the array resides in goes away, you'll be left pointing to bad things.

array of pointers in C++ and what is "BUS ERROR" [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
#include<cstdio>
#include<string>
#include<iostream>
using namespace std;
int main()
{
int a[]={0,1,2,3};
int *r[]={NULL};
for(int i=0;i<4;i++)
{
r[i]=&a[i];
cout << &a[i] << endl;
cout << a[i]<<endl;
}
for(int i=0;i<4;i++)
{
cout << r[i] << endl;
cout << *r[i] << endl;
}
return 0;
}
I have started working on the array of pointers very recently. Can someone please help me out in finding the mistake in the above program..
I attached the screenshots of the results when run on windows and linux platforms.
On Windows,the addresses of the *r[] and a[] are matching and still the values are not matching.
On linux,it says "BUS ERROR" sometimes and "Segmentation fault" sometimes.
It would be better if someone explain what the "BUS ERROR" mean? And why does it come for this program.
Your array r only has space for a single element in it, but you store 4. That overwrites memory, causing the crash.
Change this:
int *r[]={NULL};
to:
int *r[sizeof a / sizeof *a];
This makes r have the same number of elements as a, in other words 4.
int *r[]={NULL}; should be int *r[]={0, 0, 0, 0};
That will allocates space for four pointers that your following code need.
BUS ERROR: What is a bus error?
Your are not allocating enough space for your r. Try int *r[4]; and you will not get a segmentation fault.
int *r[] = {0} it's equivalent with int *r[1];
r is an array of pointers, but in your code, it has only one element. You are lucky to run it on windows but it's a undefined behavior. It might seem to work today, on your compiler, but it is not legal C or C++, and there is no guarantee that it'll still work the next time you run the program. Or that it hasn't overwritten essential data even now, and you just haven't encountered the problems that is going to cause yet.