For some reason, whenever I run this program it exits at permute(permutater, length, lenth); . This doesn't happen whenever I comment out the line and the function doesn't even run. Any help?
First thing I noticed - you're not initializing the index variable hor.
int permute(string permutater,int length,int lenth)
{
int hor,hor2,marker;
cout << length/lenth;
for (marker=0;marker !=(length/lenth);marker++)
{
hor2 = permutater[hor]; // <== hor is not initialized
permutater[hor] = permutater[hor-1];
permutater[hor] = hor2;
hor--;
cout << permutater;
}
}
hor2 = permutater[hor];
What's the value of hor?
I got the following compile errors with MSVC
error C4716: 'permute' : must return a value
warning C4700: uninitialized local variable 'hor' used
Haven't got a chance to run it yet, but did you notice that you're missing return in the permute(string permutater,int length,int lenth) function.
Also, please #include <string>
Related
I'm a newbie. For a school project, I need a typewriter, and I came down to this idea that seems good to me. But when I launch it, it says this error:
terminate called after throwing an instance of 'std::out_of_range' error
I don't know why. I think the idea is good, because when I try without the variable t, so just putting numbers in testo.erase(), it works, but I need to create a loop.
void typewriter(string testo, int tempo)
{
int i = testo.length();
int t = 0;
while (t<=i)
{
system ("CLS");
t=t+1;
testo.erase(t);
cout<<testo;
Sleep(tempo);
}
}
This is because you are erasing the characters, which shortens the string. I think that changing testo.erase(t) to test.erase(0) should fix it.
Also, as πάντα ῥεῖ said, it should be t < i instead of t <= i. But, this is an unnecessary change, as with the erasing of characters.
Thanks, I resolved it by reassigning the string testo every time I join in the while loop:
void typewriter(string testo, int tempo)
{
int i = testo.length();
int t = 0;
string testo1 = testo;
while (t<i)
{
testo1 = testo;
system ("CLS");
t=t+1;
testo1.erase(t);
cout<<testo1;
Sleep(tempo);
}
}
I am trying to find the 1D peak through Divide and Conquer technique in this particular question,
my program even though it runs,
but at the time of giving the final output it says that there has been some problem with the execution,
I have got the answer from a different method, but I would like to know where am I at fault here.
#include<iostream>
using namespace std;
int a[8];
class pg1
{
public:
int func(int n)
{
if(a[n] <= a[n+1])
{
func(n++);
}
else if(a[n] <=a [n-1])
{
func(n--);
}
else
{
return n;
}
}
};
int main()
{
pg1 ob;
for(int i=0;i<8;i++)
{
cin >> a[i];
}
int x = ob.func(4);
cout << endl << x;
return 0;
}
Input-
5
6
8
5
4
3
6
4
Errors are-
1D Peak.exe has stopped working.
A problem caused the program to stop working correctly.Windows will close the program and notify you aif a solution is available.
End Result-
Process Exited with return value 3221225725
Don't use postincrement and similar in function calls.
Here's the problem condensed down to a really simple piece of code
#include <iostream>
int test(int n){
if(n == 1){
std::cout << "Function called!";
return test(n++);
}else{
return 0;
}
}
int main() {
test(1);
return 0;
}
Before you run this, ask yourself what you expect to happen here. Did it do what you thought?
When you run this you'll see that the code doesn't terminate properly. The output shows the function gets called infinitely many times, eventually the stack runs out of space and the program crashes.
You can see this code in action here: http://ideone.com/QL0jCP
In your program you have the same problem:
int func(int n)// say n = 4
{
if(a[n] <= a[n+1])//say this is true
{
func(n++); //this calls func(4) THEN increments n afterwards
}
This calls func with the same value over and over.
The solution is to not use postincrement or postdecrement in your function calls. These create hard to diagnose bugs as you have seen in this question. Just a simple func(n+1) is all you need. If you needed to use the variable later then just create an explicit variable to do that, it's much cleaner coding style (as this problem you ran into here shows).
After you fix this you'll need to fix your array bounds checking.
if(a[n] <= a[n+1])
If n is the last spot in the array you suddenly are trying to access one place past the end of the array, if you are lucky you get a segfault and a crash, if you are unlucky you get some bug that messes up your system that is hard to find. You want to check the values are valid.
I'm starting to study recursion in C++ and I'm facing a problem that I can't figure out.
What's happening is that Eclipse and g++ are saying that my variable type is not matching with the function declaration but I believe it does.
Please take a look, first at the screen dump from Eclipse, showing the error:
And also the code in textual rather than graphical form:
int saida(char **matriz, char dir,int entrada_l, int entrada_c,int* zeros,int** tracker) {
int flag3,flag4,tamanho_martiz = 8;
int resp;
if(dir == 'c'){
if(matriz[entrada_l++][entrada_c] == '0'){
resp = saida(matriz, 'c',entrada_l,entrada_c,&zeros,tracker);
}
}
return 0;
}
You pass the address of zeros in your recursive call:
resp = salida (matrix, 'c', entrada_l, entrada_c, &zeros, tracker);
// ^
That's an extra level of indirection from what it expects, an int *, while you're giving it an int **.
Get rid of the & in the call and that should fix the problem.
#include <iostream>
using namespace std;
void main()
{
int leftover;
int gold = 3900;//satisfies the if else statement
if( gold>=4100){//successfully build item
leftover = gold-4100;
}
else if(4100>gold>=3500){
leftover = gold-3500;
}
cout << leftover << endl;
system("pause");
}
This code doesn't work, it will show that leftover is used without being initialized. But when I changed the value of gold(etc 4200) to satisfy the if statement, it will work, displaying the remainder after gold has been deducted from 4100. I am just learning c++ in school so I am not familiar with if and if else statements yet so many thanks for telling me what went wrong!
4100>gold>=3500 doesn't do what you think. It's evaluated as (4100>gold) >= 3500, which depending on the value of gold can be 0 >= 3500 or 1>3500. Look up operator precedence.
You probably want
(4100>gold) && (gold>=3500)
If you don't initialize the value and the if statements fail, then you cout null
You have two suggestions here:
FIRST:
int leftover = -1; //Initialize the value
SECOND:
else { leftover = 0; } //Default the value if the if case fails
Yea I made a VERY careless mistake, the only problem is 4100>gold>3500 will never get evaluated.
Thanks to all who answered and pointed out to use AND gate instead of shared operands!
I have the following code compiled in linux terminal (c++ in linux) and am using OpenCv 2.4.3.
However, am getting a segmentation fault in run time and I really have no clue as to why. I have placed differnt cout statements to know if the program processed to the particular stage but in vain. Could you please help me? Please explain me what exactly is this segmentation fault. Am stuck here for a long time.
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <iostream>
#include <stdlib.h>
using namespace cv;
using namespace std;
int main()
{
cout<<"check"<<flush;
Mat src,src_gray,dst;
int kernel_size = 3;
int scale = 1;
int delta = 0;
int ddepth = CV_16S;
char* window_name = "sharpness estimate";
int freq,rows,cols =0;
double *estimate,*min = 0;
Point *minLoc,*maxLoc = 0;
src = imread("/home/siddarth/examplescv/erez images/image53.jpg");
if( !src.data )
{
return -1;
}
namedWindow(window_name,CV_WINDOW_AUTOSIZE);
Mat abs_dst;
cvtColor(src,src_gray,CV_RGB2GRAY);
Laplacian(src_gray,dst,ddepth,kernel_size,scale,delta,BORDER_DEFAULT);
convertScaleAbs(dst, abs_dst);
minMaxLoc(dst,min,estimate,minLoc,maxLoc,noArray());
Size s = dst.size();
rows = s.height;
cols = s.width;
cout<<rows<<endl<<cols<<endl;
for(int i=0;i<=rows;i++)
{
for(int j=0;j<=cols;j++)
{
if(dst.at<double>(i,j) >= *estimate-100
&& dst.at<double>(i,j) <= *estimate+100)
{
cout<<freq++;
}
}
}
cout<<"estimate :"<<*estimate<<endl;
cout<<"frequency :"<<freq<<endl;
imshow(window_name,abs_dst);
waitKey(1000);
return 0;
}
The code doesn't cross the first "check" print statement just after the main function declaration. That is the confusing issue. But once I flushed the first print statement, it got executed. I am still facing issues.
Make sure you insert std::endl into cout so that the buffer is flushed. This will probably be why you're not seeing any output.
One immediate issue is that your for loops check the condition with <=, meaning that you're probably going one past the end. But since you're using at, you should have an exception thrown (assuming this Mat type acts like a standard container).
Also, you're creating lots of pointers to pass as some function arguments (for example, double* estimate). This doesn't actually give you a double object though, just a pointer. Unless the function you're passing them to is allocating a double for you (which I hope it's not), you're doing it wrong. You should be doing:
double estimate;
minMaxLoc(/* ... */, &estimate, /* ... */);
You'll need to do that with all of the values you're getting through output parameters.
Another thing to note: Doing int i, j = 0; only initialises j to 0, but not i. You need to do int i = 0, j = 0;.
Okay, I'm going to explain why fixing the initialisers works. I had to look up the definition of minMaxLoc to see what happens. Basically, the function is something like the following:
void setToFive(int* x)
{
if (x) {
*x = 5;
}
}
This function will take a pointer to an int, and then set that int to the value 5. However, if the pointer passed is a null pointer, the value will not be set (otherwise there'll be undefined behaviour because you're derefencing a null pointer). Basically, passing a null pointer says "I don't care about this value so don't give it to me".
Now when you were initialising your pointers, you were doing:
double *estimate, *min = 0;
This only sets min to the null pointer. Since estimate is left uninitialized, you can't rely on its value being null. You need to provide an initialiser for each declarator:
double *estimate = 0, *min = 0;
Thanks to #sftrabbit. The problem was the initialization. instead of
int freq,rows,cols=0;
The change was
int freq=0,rows=0,cols=0;
this removed the segmentation fault. Thanks a lot for your help :).
Since you are in a Linux environment, you can use valgrind to find out exactly where the segmentation fault is happening. Just type valgrind before the name of the program, or the way you execute your program. For example, if you execute your program with the following command:
hello -print
issue the following command instead:
valgrind hello -print
I see you already solved this one, but this may be helpful in the future!