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.
Related
This question already has answers here:
No out of bounds error
(7 answers)
Closed 1 year ago.
I'm working on dynamic arrays for my c++ course, but I'm confused about the behavior of my dynamic arrays. For example, if I run this code:
int* myDynamicArr = new int[3];
for (int i = 0; i < 10; i++)
{
myDynamicArr[i] = i + 1;
cout << myDynamicArr[i] << endl;
}
I would expect it to not work since I only declared it as size 3. But when I run it, it prints out 0-9. Same thing if I do this:
char* myCharArr = new char[2];
strcpy(myCharArr, "ThisIsALongString");
cout << myCharArr;
It prints the full string even though it seems like it should fail. Can anyone explain what I'm doing wrong here? Thanks!
C++ does not perform bounds checking on arrays. So when you read or write past the bounds of an array you trigger undefined behavior.
With undefined behavior, your program may crash, it may output strange results, or it may (as in your case) appear to work properly.
Just because it could crash doesn't mean it will.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
#include <iostream>
using namespace std;
int main()
{
int arr,i=0,frequancy,y,X,l;
int V[arr];
cout<<"Enter the size of an array: ";
cin>>arr;
cout<<"Enter all "<<arr<<" elements in array: ";
for(i=0;i<=arr-1;i++)
cin>>V[i];
int a[arr]={0};
cout<<"Frequency of all "<<arr<<" elements in array:"<<endl;
for(i=0;i<arr;i++)
{
int count=0;
if (a[i]!=1)
{
for (int j=0;j<arr;j++)
{
if(V[i]==V[j])
{
count++;
a[j]=1;
}
}
if (count>1||count==1)
{
cout<<V[i]<<" occurs "<<count<<" times "<<endl;
}
}
}
return 0;
}
//this is the answer
Enter the size of an array: 9
Enter all 9 elements in array: 1
1
2
3
1
5
3
12
1
Frequency of all 9 elements in array:
1 occurs 4 times
2 occurs 1 times
3 occurs 2 times
5 occurs 1 times
12 occurs 1 times
So there are a few questions that I don't understand that well and I need someone to explain what is going on with it, please.
I don't understand why we have to initialize this(int a[arr]={0}) to 0, I asked my prof about it be he said it has to be like that. which doesn't answer my question:'C.
I have a problem with the bottom part of the code, I kinda understand a bit but if someone can help me that would help a lot Thank you!!!!
int arr/*...*/;
int V[arr];
cin>>V[i];
This program is badly broken.
Problem 1: The size of an array variable must be a compile time constant in C++. arr is not a compile time constant value. Violating this rule makes the program ill-formed, which means that compilers aren't required to compile it. You should avoid this.
Solution: If you need an array whose size is determined at runtime, then you should allocate the array dynamically. Simplest way to achieve that is to use the std::vector template from the standard library.
Problem 2: The behaviour of a program that reads an indeterminate value is undefined. Undefined behaviour means that there are no guarantees about the behaviour of the program whatsoever. This is very bad and should be avoided.
arr has an indeterminate value when you use it. The behaviour of the program is undefined. I repeat: This is very bad.
C++ is not a "data-flow" language. You cannot simply use a variable and initialise it after the usage. The program won't automatically stop, create a thread and wait for the later initialisation to proceed further.
Solution: Initialise before use.
I don't understand why we have to initialize this(int a[arr]={0}) to 0
Later on in the program, the values of that array are read (a[i]!=1). If you don't initialise the values before using them, then the behaviour of the program is undefined. See the previous paragraph.
Presumably, the elements of the array are initialised to zero in order to avoid that undefined behaviour.
Note that it is redundant to initialise the first element of the array explicitly to zero, and value initialise the rest, because those achieve the same thing. Thus, a simpler way to achieve the same is to value initialise all of the elements by not providing an initialiser for any of them:
constexpr int arr = 42;
int a[arr] {};
I have a problem with the bottom part of the code
The first step to solve that problem is to figure out why you think that you have a problem, and what kind of problem it could be.
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.
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.
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.