I'm trying to fix a SIGSEGV error in my program. I am not able to locate the site of error. The program compiles successfully in Xcode but does not provide me the results.
The goal of the program is to check whether the same element occurs in three separate arrays and return the element if it is more than 2 arrays.
#include <iostream>
using namespace std;
int main()
{
int i = 0 ,j = 0,k = 0;
int a[5]={23,30,42,57,90};
int b[6]={21,23,35,57,90,92};
int c[5]={21,23,30,57,90};
while(i< 5 or j< 6 or k< 5)
{
int current_a = 0;
int current_b = 0;
int current_c = 0;
{ if (i<5) {
current_a = a[i];
} else
{
;;
}
if (j<6)
{
current_b = b[j];
} else
{
;;
}
if (k<5)
{
current_c= c[k];
} else
{
;;
}
}
int minvalue = min((current_a,current_b),current_c);
int countoo = 0;
if (minvalue==current_a)
{
countoo += 1;
i++;
}
if (minvalue==current_b)
{
countoo +=1;
j++;
}
if (minvalue==current_c)
{
countoo += 1;
k++;
}
if (countoo >=2)
{
cout<< minvalue;
}
}
}
I am not getting any output for the code.
This is surely not doing what you want
int minvalue = min((current_a,current_b),current_c);
If min() is defined meaningfully (you really should provide an MCVE for a question like this), you want
int minvalue = min(min(current_a,current_b),current_c);
This will result in the minimum of the minimum of (a and b) and c, i.e. the minimum of all three, instead of the minimum of b and c. The comma operator , is important to understand this.
This seems to be a flag/counter to make a note across loop executions or count something
int countoo = 0;
It can however not work if you define the variable inside the loop.
You need to move that line BEFORE the while.
With this line you do not prevent the indexes to leave the size of the arrays,
that is very likely the source for the segfault.
while(i< 5 or j< 6 or k< 5)
In order to prevent segfaults, make sure that ALL indexes stay small enough,
instead of only at least one.
while(i< 5 && j< 6 && k< 5)
(By the way I initially seriously doubted that or can compile. I thought
with a macro for or it could, but I do not see that. It could be a new operator in a recent C++ standard update which I missed...
And it turns out that it is the case. I learned something here.)
This should fix the segfault.
To achieve the goal of the code I think you need to spend some additional effort on the algorithm. I do not see the code being related to the goal.
Related
The point of this program is to output whether a series of digits (the number of digits undefined) is sorted or not (largest to smallest or smallest to largest).
I have defined my array in my function parameter, and I am trying to use a for loop to store the user's input, as long as it is above 0, in said array.
However, I am getting the error argument of type int is incompatible with parameter of type int*.
The exact error is the argument of type int is incompatible with parameter of type int*.
It is referring to line 22 and 23, these two;
isSorted(list[2000]); and
bool is = isSorted(list[2000]);.
I know this means my for loop is assigning a single value to my variable repeatedly from reading similar questions however I can not figure out how to fix this.
#include <iostream>
using namespace std;
bool isSorted(int list[]);
int main()
{
int i;
int list[2000];
int k = 0;
for (i = 0; i < 2000; i++)
{
int j;
while (j > 0)
{
cin >> j;
list[i] = j;
}
}
isSorted(list[2000]);
bool is = isSorted(list[2000]);
if (is == true)
cout << "sorted";
else
cout << "unsorted";
return 0;
}
bool isSorted(int list[])
{
int i = 0;
for (i = 0; i < 2000; i++)
{
if (list[i] > list[i + 1] || list[i] < list[i - 1])
{
return false;
}
else
return true;
}
}
I removed unused variable k.
Made 2000 parameterized (and set to 5 for testing).
In isSorted you are not allowed to return
true in the else as if your first element test would end in else you would return true immediately not testing other elements. But those later elements can be unsorted as well.
In isSorted you are not allowed to run the loop as for(i = 0; i < 2000; i++), because you add inside the for loop 1 to i and end up querying for i == 1999 list[2000], which is element number 2001 and not inside your array. This is correct instead: for (i = 0; i < 1999; i++). You also do not need to check into both directions.
You cannot call isSorted(list[2000]) as this would call is sorted with an int and not an int array as parameter.
You write int j without initializing it and then query while j > 0 before you cin << j. This is undefined behaviour, while most likely j will be zero, there is no guarantee. But most likely you never enter the while loop and never do cin
I renamed the isSorted as you just check in your example for ascending order. If you want to check for descending order you are welcome to train your programming skills and implementing this yourself.
Here is the code with the fixes:
#include <iostream>
using namespace std;
bool isSortedInAscendingOrder(int list[]);
const int size = 5; // Set this to 2000 again if you want
int main()
{
int i;
int list[size];
for (i = 0; i < size; i++)
{
int j = 0;
while(j <= 0)
{
cin >> j;
if(j <= 0)
cout << "rejected as equal or smaller zero" << endl;
}
list[i] = j;
}
if (isSortedInAscendingOrder(list))
cout << "sorted" << endl;
else
cout << "unsorted" << endl;
return 0;
}
bool isSortedInAscendingOrder(int list[])
{
for (int i = 0; i < size -1; i++)
{
if (list[i] > list[i + 1])
{
return false;
}
}
return true;
}
This is a definition of an array of 2000 integers.
int list[2000];
This is reading the 2000th entry in that array and undefined, because the highest legal index to access is 1999. Remember that the first legal index is 0.
list[2000]
So yes, from point of view of the compiler, the following only gives a single integer on top of being undefined behaviour (i.e. "evil").
isSorted(list[2000]);
You probably should change to this, in order to fix the immediate problem - and get quite close to what you probably want. It names the whole array as parameter. It will decay to a pointer to int (among other things loosing the information of size, but you hardcoded that inside the function; better change that by the way).
isSorted(list);
Delete the ignored first occurence (the one alone on a line), keep the second (the one assigning to a bool variable).
On the other hand, the logic of a your sorting check is flawed, it will often access outside the array, for indexes 0 and 1999. I.e. at the start and end of your loop. You need to loop over slightly less than the whole array and only use one of the two conditions.
I.e. do
for (i = 1; i < 2000; i++)
{
if (list[i] < list[i - 1])
/* ... */
The logic for checking ascending or descending sorting would have to be more complex. The question is not asking to fix that logic, so I stick with fixing the issues according to the original version (which did not mention two-way-sorting).
You actually did not ask about fixing the logic for that. But here is a hint:
Either use two loops, which you can break from as soon as you find a conflict, but do not return from the fuction immediatly.
Or use one loop and keep a flag of whether ascending or descending order has been broken. Then return true if either flag is still clear (or both, in case of all identical values) or return false if both are set.
I am a beginner in c++ and I am having problems with making this code work the way I want it to. The task is to write a program that multiplies all the natural numbers up to the loaded number n.
To make it print the correct result, I divided x by n (see code below). How can I make it print x and not have to divide it by n to get the correct answer?
#include<iostream>
using namespace std;
int main(){
int n,x=1;
int i=0;
cout<<"Enter a number bigger than 0:"<<endl;
cin>>n;
while(i<n){
i++;
x=i*x;
};
cout<<"The result is: "<<x/n<<endl;
return 0;
}
At very first a principle you best get used to as quickly as possible: Always check user input for correctness!
cin >> n;
if(cin && n > 0)
{
// valid
}
else
{
// appropriate error handling
}
Not sure, why do you need a while loop? A for loop sure is nicer in this case:
int x = 1;
for(int i = 2; i < n; ++i)
x *= i;
If you still want the while loop: Start with i == 2 (1 is neutral anyway) and increment afterwards:
i = 2;
while(i < n)
{
x *= i;
++i;
}
In case of n == 1, the loop (either variant) simply won't be entered and you are fine...
You already have two very good options, but here is an other one you might want to take a look at when you are at ease enough in programming :
unsigned factorial(unsigned value)
{
if (value <= 1)
{
return 1;
}
else
{
return value * factorial(value - 1);
}
}
It's a recursive function, which is kind of neat when used in proper moments (which could not be the case here unfortunately because the execution stack might get so big you fill your memory before you're done. But you can check it out to learn more about recursive functions)
When your memory is full, you then crash your app with what is called actually a stack overflow.
How can I make it so that in the last cout I can only put x and not have to divide x by n to get the correct answer?
It will be better to use a for loop.
// This stops when i reaches n.
// That means, n is not multiplied to the result when the loop breaks.
for (int i = 1; i < n; ++i )
{
x *= i;
}
cout << "The result is: " << x <<endl;
I picked up "Programming Principles and Practice using C++", and was doing an early problem involving the Sieve of Eratosthenes, and I'm having unexpected output, but I cannot pin down exactly what the problem is. Here is my code:
#include <iostream>
#include <vector>
int main()
{
std::vector<int> prime;
std::vector<int> nonPrime;
int multiple = 0;
for(int i = 2; i < 101; i++) //initialized to first prime number, i will
// be the variable that should contain prime numbers
{
for(int j = 0; j < nonPrime.size(); j++) //checks i against
// vector to see if
// marked as nonPrime
{
if(i == nonPrime[j])
{
goto outer;//jumps to next iteration if number
// is on the list
}
}
prime.push_back(i); //adds value of i to Prime vector if it
//passes test
for(int j = i; multiple < 101; j++) //This loop is where the
// sieve bit comes in
{
multiple = i * j;
nonPrime.push_back(multiple);
}
outer:
;
}
for(int i = 0; i < prime.size(); i++)
{
std::cout << prime[i] << std::endl;
}
return 0;
}
The question only currently asks me to find prime numbers up to 100 utilizing this method. I also tried using this current 'goto' method of skipping out of a double loop under certain conditions, and I also tried using a Boolean flag with an if statement right after the check loop and simply used the "continue;" statement and neither had any effect.
(Honestly I figured since people say goto was evil perhaps it had consequences that I hadn't foreseen, which is why I tried to switch it out) but the problem doesn't call for me to use modular functions, so I assume it wants me to solve it all in main, ergo my problem of utilizing nested loops in main. Oh, and to further specify my output issues, it seems like it only adds multiples of 2 to the nonPrime vector, but everything else checks out as passing the test (e.g 9).
Can someone help me understand where I went wrong?
Given that this is not a good way to implement a Sieve of Eratosthenes, I'll point out some changes to your code to make it at least output the correct sequence.
Please also note that the indentation you choose is a bit misleading, after the first inner loop.
#include <iostream>
#include <vector>
int main()
{
std::vector<int> prime;
std::vector<int> nonPrime;
int multiple = 0;
for(int i = 2; i < 101; i++)
{
// you can use a flag, but note that usually it could be more
// efficiently implemented with a vector of bools. Try it yourself
bool is_prime = true;
for(int j = 0; j < nonPrime.size(); j++)
{
if(i == nonPrime[j])
{
is_prime = false;
break;
}
}
if ( is_prime )
{
prime.push_back(i);
// You tested 'multiple' before initializing it for every
// new prime value
for(multiple = i; multiple < 101; multiple += i)
{
nonPrime.push_back(multiple);
}
}
}
for(int i = 0; i < prime.size(); i++)
{
std::cout << prime[i] << std::endl;
}
return 0;
}
I am trying to implement merge sort for my algorithm analysis class and every time I run it there is a segmentation fault. I think the problem is when i split the vector in the merge_sort function but I cannot find the problem. Help would be really appreciated guys.
template <typename T>
std::vector<int> merge(std::vector<T>& A,std::vector<T>& B)
{
int a_size = A.size();
int b_size = B.size();
std::vector<int> C(a_size+b_size,0);
//int *c = new int[b_size+a_size];
int i =0,j =0,k=0;
while(i < a_size && j < b_size)
{
if(A[i]<B[j])
{
C[k] = A[i];
k++;
i++;
}
else
{
C[k] = B[j];
k++;
j++;
if(i!=a_size)
{
for(;i<a_size;i++,k++)
{
//copy rest of a to c
C[k] = A[i];
}
}
if(j != b_size)
{
for(;j<b_size;k++,j++)
{
//copy the rest of b to c
C[k] = B[j];
}
}
}
}
return C;
}
// Merge sort implementation
template <typename T>
void merge_sort(std::vector<T>& vector)
{
// TODO implement merge sort
int vector_size = vector.size();
int big_vector_index = 0;
int half_size = (int)vector_size/2;
int remainder = vector_size%2;
std::vector<int> left(half_size,0);
std::vector<int> right(half_size+remainder,0);
for(int l = 0;big_vector_index<half_size;l++,big_vector_index++)
{
left[l] = vector[big_vector_index];
}
for(int m = 0;big_vector_index<vector_size;m++,big_vector_index++)
{
right[m] = vector[big_vector_index];
}
big_vector_index = 0;
merge_sort(left);
merge_sort(right);
vector = merge(left,right);
}
I took a look at your code, and the majority of it is correct from my testing. I don't want to do your coursework for you but maybe a couple of hints in the right direction will help.
For your original question about the segfault that you got, PaulMcKenzie, Jim Lewis, and Tahlil are right, merge_sort() needs a base condition (base case) to check whether or not the recursion should continue, so it doesn't run forever and/or until your computer runs out of memory (which is what is happening in your case). In general, any recursive function should have a base case.
Also, you should take a look at your merge function as well. It has all the parts of a correct merge function, but some parts of it run a bit earlier/more often than you want them too. I don't want to give too much away since it's for class, but if you fix the segfault problem and are still getting strange answers, take a look at it.
The program below is suppose to be looking for "Pair's" and "Flush's". It iterates through 10 Trials consisting of 10,000 hands, each hand consisting of 5 cards. The result should (of course it doesn't right now) consist of 10 rows reflecting unique results for each trial. I am stuck...thanks in advance.
#include "card.h"
#include "deck.h"
#include "game1.h"
#include <iostream>
#include <time.h>
#include <stdlib.h>
using namespace std;
int main() {
int pair = 0;
int flush = 0;
int h; //Hands
int c; //Cards
int t; //Trials
const int MAXTRIALS = 10;
const int MAXHANDS = 10000;
const int MAXCARDS = 5;
const int MAXSHUFFLE = 100;
Deck myDeck;
Card myCards[MAXCARDS];
myDeck.shuffle(MAXSHUFFLE); //How often would you shuffle?
srand((unsigned)time(NULL)); //Randon initilizer
for (t = 0 ; t < MAXTRIALS; ++t) //Outermost loop for the Trials
{
for (h = 0; h < MAXHANDS; ++h) //InnerLoop for Hands
{
myCards[0] = myDeck.getCard();
for (c = 1; c < MAXCARDS; ++c) //InnerMost Loop for Cards
{
myCards[c] = myDeck.getCard();
if (myCards[c].getValue() == myCards[0].getValue())
{
pair++;
}
if (myCards[c].getSuit() == myCards[0].getSuit())
{
flush++;
}
myDeck.addCard(myCards[c]);
c++;
}
myDeck.shuffle(MAXSHUFFLE);
h++;
}
cout << "pairs: " << pair << "\tflushes: " << flush << endl;
}
cin.get();
}
If I understand your question, "the result should ... consist of 10 rows reflecting unique results for each trial", the problem is simply that you don't reset the pair and flush counter variables between each trial. Something like the following where the 'trial' for loop starts should do the trick:
for (t = 0 ; t < MAXTRIALS; ++t)
{
pair = 0;
flush = 0;
// the remainder as is...
With a lot of guessing what exactly should happen...
1) Is it made sure, that myDeck.getCard() does not draw the same card twice? Or does it not matter for your task?
2) What is myDeck.addCard(myCards[c]) exactly doing?
3) Why do you increment the loop counter a second time? c++
If this is made sure, you are only comparing against the first card. If you want to compare a complete hand, your code should look something like this:
// first draw the complete hand
for(int card = 0; card < MAX_CARDS; ++card)
{
myCards[card] = myDeck.getCard();
}
// now that we have the full hand, compare each card against each other card
for(int start = 0; start < MAXCARDS-1; ++start)
{
for(int compare = start+1; compare < MAXCARDS; ++compare)
{
if (myCards[start].getValue() == myCards[compare].getValue())
{
pair++
}
// do similar for flushs
}
}
I didn't test this code, but this should give you a start.
This would count every pair, even if there are two pairs in one hand. It would need additional code to break out of the loops, if a pair was found.
btw: looks like homework to me...
The c++ and h++ are a little bit suspicious (did you really mean to only touch every other item)? But without more information as to what you are observing, it would be hard to give a definitive answer.
Also, some minor stylistic recommendations regarding your code:
I recommend putting off the declaration of "h", "c", and "t" to the first point at which they are needed, so I would declare them in the for-loop (e.g. "for (int h = 0; h < ... ; h++)").
It is more idiomatic to use static_cast in C++ code (i.e. srand(static_cast(time(NULL)))), than it is to use a C-style cast, however both forms are correct.