Program triggers breakpoint; doesn't run - c++

Hi I'm a beginner level programmer and I have an issue with a program I've been working on. The point is to create a an individual class that has an array consisting of random generated numbers as one private variable, a size for the array, and a number representing the fitness of the individual through the use of the array.
It utilizes a header file, the source file for the header, and source file to test the header. For some reason, whenever I try to compile I reach a breakpoint, and Visual Studio doesn't tell me what the error is. I suspect it has something to do with the private pointer in my class but I don't know why or how to fix the error.
Header
#ifndef INDIVIDUAL_H
#define INDIVIDUAL_H
class individual
{
int size;
double fitness;
double* genotype;
public:
individual(int pSize = 10);
individual(const individual& copy);
~individual();
double* getGenotype();
double getFitness();
int getSize();
void mutation();
void crossover(individual a);
};
#endif
Header source
#include <iostream>
#include <string>
#include <stdlib.h>
#include <time.h>
#define M_PI 3.14159265358979323846
#define M_E 2.71828182845904523536
#include <cmath>
#include "individual.h"
using namespace std;
double RandomFloat(double min = -32.768, double max = 32.768)
{
min = min;
max = max;
unsigned int seed;
seed = (unsigned int) time(0) + rand();
srand(seed);
double r = (double)rand() / (double)RAND_MAX;
return min + r * (max - min);
}
double Fitness(double a[], int size)
{
double fitness;
double firstSum, secondSum;
firstSum = 0;
for(int i = 0; i<size; i++)
{
firstSum += a[i]*a[i];
}
firstSum /= size;
secondSum = 0;
for(int i = 0; i<size; i++)
{
secondSum += cos(2*M_PI*a[i]);
}
secondSum /= size;
fitness = -20*exp(-0.2*sqrt(firstSum) - exp(secondSum) + 20 + M_E);
return fitness;
}
individual::individual(int pSize)
{
size = pSize;
genotype = nullptr;
genotype = new double(size);
for(int i = 0; i<size; i++)
{
genotype[i] = RandomFloat();
}
fitness = Fitness(genotype,size);
}
individual::individual(const individual& copy)
:size(copy.size),genotype(new double[copy.size])
{
std::copy(copy.genotype, copy.genotype + copy.size, genotype);
}
individual::~individual()
{
delete[] genotype;
}
double* individual::getGenotype()//returns a pointer
{
return genotype;
}
double individual::getFitness()
{
return fitness;
}
int individual::getSize()
{
return size;
}
void individual::mutation()
{
int first, second;
double temp;
first = (int)RandomFloat();
second = (int)RandomFloat();
temp = genotype[first];
genotype[first] = genotype[second];
genotype[second] = temp;
}
void individual::crossover(individual a)
{
int crossPoint = size/3 - 1;
for(int i = crossPoint; i<size; i++)
{
double temp1;
temp1 = 0;
temp1 = genotype[i];
genotype[i] = a.genotype[i];
a.genotype[i] = temp1;
}
}
Driver source
#include <iostream>
#include <string>
#include <stdlib.h>
#include <cmath>
#include <vector>
#include "individual.h"
#define M_PI 3.14159265358979323846
#define M_E 2.71828182845904523536
using namespace std;
int main()
{
individual test;
int size = test.getSize();
cout << size << endl;
for(int i = 0; i<size; i++)
{
cout << test.getGenotype()[i] << endl;
}
return 0;
}
I've tried searching for possible solutions (added the copy constructor and destructor) and nothing seems to resolve the problem.
Any help would be much appreciated.

To allocate an array of double
Change:
genotype = new double(size); // this initialize one double and initialize value to size
TO
genotype = new double[size]; // this creates an array which size is 'size'
Your code overruns memory when you only allocate one double and write data to memory
for(int i = 0; i<size; i++)
{
genotype[i] = RandomFloat();
}

Related

I cant seem to assign a pointer an array and then change the contents of the array

I couldn't figure out how to make a function return an array so instead I decided to try and pass an empty array (of the correct size) into my function and than reassign the address to a different array of the same size. Is this at all a way to do things??? Can someone show me what to do? if this is wrong can you fill me in on how to do this?
here is my code:
#include <iostream>
#include <cmath>
using namespace std;
void ArrayFiller(int earray,int s, int f){
int *ptrarray = &earray;
int prenum_size = std::abs(s) + f - 1;
int pre_num[prenum_size];
for(int x=s;x<f;x++){
pre_num[x+std::abs(s)] = x;
}
*ptrarray = pre_num;
}
int Main(){
int first = -10;
int second = 15;
int temp[abs(first) + abs(second)];
ArrayFiller(temp, first, second);
int n = sizeof(temp)/sizeof(temp[0]);
for (int i = 0; i < n; i++) {
cout << temp[i] << ' ';
}
return 0;
}
I think you're looking for something like this:
#include <iostream>
#include <cmath>
using namespace std;
void ArrayFiller(int earray[],int s, int f){
for(int x=s;x<f;x++){
earray[x+(std::abs(s))] = x;
}
}
int main(){
int first = -10;
int second = 15;
int n = abs(first)+abs(second);
int* temp = new int[n];
ArrayFiller(temp, first, second);
for (int i = 0; i < n; i++) {
cout << temp[i] << ' ';
}
delete [] temp;
return 0;
}

POSIX pthread_create scrambles the values of variables in a struct, how to avoid that?

So I have my program here:
#include <iostream>
#include <string>
#include <pthread.h>
#include <unistd.h>
#include <math.h>
#include <stdlib.h>
using namespace std;
int const size = 3;
struct Arguments{
int array[];
float result1[];
float result2[];
};
//void calc(int arr[], float rarr1[], float rarr2[], int size);
void* calc(void *param);
int main(int argc, char *argv[]){
time_t t;
srand((unsigned) time(&t));
int arr[size][size] = {};
float rarr1[size][size-1] = {};
float rarr2[size][size-1] = {};
for(int x = 0; x < size; x++){
for(int y = 0; y < size; y++){
int number = rand()%10;
arr[x][y] = number;
}
}
for(int x = 0; x < size; x++){
for(int y = 0; y < size; y++){
cout << arr[x][y] << " ";
}
cout << endl;
}
cout << endl;
/////////////////////////////////////////
pthread_t child;
struct Arguments input;
for(int i = 0; i < size; i++){
input.array[i] = arr[0][i];
}
pthread_create(&child, NULL, calc, (void*)&input);
pthread_join(child, NULL);
//calc(&input);
for(int i = 0; i < size-1; i++){
rarr1[0][i] = input.result1[i];
cout << "Test: " << rarr1[0][i] << endl;
}
//////////////////////////////////
return 0;
}
//void calc(int arr[], float rarr1[], float rarr2[], int size){
void* calc(void *param){
struct Arguments *input = (struct Arguments*)param;
int arr1[] = {};
float rarr1[] = {};
float rarr2[] = {};
for(int i = 0; i < size; i++){
arr1[i] = input->array[i];
}
for(int i = 0; i < size; i++){
int a = arr1[i];
int b = arr1[i+1];
int difference = a-b;
if(difference < 0){
difference = difference * -1;
}
float euc = 1 + pow(difference, 2);
euc = sqrt(euc);
rarr1[i] = euc;
}
for(int i = 0; i <size-1; i++){
input->result1[i] = rarr1[i];
}
for(int i = 0; i <size-1; i++){
int a = arr1[i];
int b = arr1[i+1];
int difference = a-b;
if(difference < 0){
difference = difference * -1;
}
float apar = (difference/rarr1[i]);
float result = asin(apar);
result = result*(180/3.14);
rarr2[i] = result;
}
return NULL;
}
The important part that causes the trouble is between ////// lines but I left the rest of the code for the context, since it might be useful.
So I have the function calc(param); that does the important calculation in the program.
It is working just fine as long as I call it myself (by actually including the function call in the code) and the test loop right after it gives the correct results.
However, when I try to use pthread_create(); to create a new thread that will take care of executing that function, the test loop spits out nonsense and some random huge numbers different each time.
It's kinda weird because the code compiles either way, and literally the only thing that I change is these 2 lines.
What am I doing wrong and why the function spits out garbage when started by the Pthread? Is there a way to fix it?
Ok so if anyone's having a similar problem:
Declare the size of arrays no matter what. It turns out that my program didn't work properly because I initialized my result arrays as float result1[]; instead of float result1[size];

What's wrong on passing this double pointer and get the value?

I'm new/noob programmer of C++, and I've this problem. I want to pass a pointer of double to a function (which will process some data on it) and read (after the process) a fixed value of that "array". I've do this:
void ReadDoubles(double* samples, int size)
{
for (int i=0; i < size; ++i)
{
*samples = i*10.1;
samples++;
}
}
int main()
{
int size = 10;
double *values=0;
ReadDoubles(values, size);
cout << *(values+3);
}
BUt of course it seems I can't init the pointer that way. I think I need to init the pointer allocating 10 values? Tried:
double *values[size];
but that's not the solution. How would you do this simple task?
You need to allocate the array at first. Here you are
#include <iostream>
void ReadDoubles( double* samples, size_t size )
{
for ( size_t i = 0; i < size; ++i )
{
*samples = i*10.1;
samples++;
}
}
int main()
{
size_t size = 10;
double *values = new double[size];
// ^^^^^^^^^^^^^^^^
ReadDoubles( values, size );
std::cout << *(values+3) << std::endl;
delete []values;
}
The program output is
30.3
If you don't want to use the operator new then there are two general approaches. Either you can declare an array as for example
int main()
{
const size_t size = 10;
//^^^^
double values[size];
// ^^^^^^^^^^^^
ReadDoubles( values, size );
std::cout << *(values+3) << std::endl;
}
or you can use standard class std::vector<double>.In this case the function should be rewritten appropriately.
For example
#include <iostream>
#include <vector>
void ReadDoubles( std::vector<double> &samples, size_t size )
{
samples.resize( size );
for ( size_t i = 0; i < size; ++i )
{
samples[i] = i*10.1;
}
}
int main()
{
size_t size = 10;
std::vector<double> values;
ReadDoubles( values, size );
std::cout << values[3] << std::endl;
}
If you are not allowed to change the RealDoubles function and you must have a function return the size then the following should work:
#include <string>
#include <iostream>
#include <math.h>
#include <cmath>
using namespace std;
void ReadDoubles(double* samples,int size)
{
for (int i=0; i < size; ++i) {
*samples = i*10.1;
samples++;
}
}
int get_size()
{
return 10;
}
int main()
{
int size = get_size(); // get size from function
//double *values=0;
double *values = new double[size] {0}; // Use new to allocate array. Optional: use {0} to init first element to 0, others default initialized to 0
ReadDoubles(values,size);
cout << *(values+3);
delete[] values;
}
If you prefer to avoid new and delete then you can let a std::vector manage the container for you:
#include <string>
#include <iostream>
#include <math.h>
#include <cmath>
#include <vector>
using namespace std;
void ReadDoubles(double* samples,int size)
{
for (int i=0; i < size; ++i) {
*samples = i*10.1;
samples++;
}
}
int get_size()
{
return 10;
}
int main()
{
int size = get_size(); // get size from function
//double *values=0;
std::vector<double> value_container(size,0); // vector will do the new and delete for us
double *values = value_container.data();
ReadDoubles(values,size);
cout << *(values+3);
} // vector destructor will do delete when it goes out of scope

Passing an array as a parameter to a function

So I'm doing a programming assignment and I've ran into an issue, when every I attempt to pass the arrays to the header file, I receive an error while compiling, I'm not too clear as how to do this and would much appreciate so assistance in passing these arrays.
Here is the Header file "sorting.h"
#include <iostream>
#include <cstdlib>
using namespace std;
int cost = 0;
void bubble(int Ar[],int N)
{
cost=0;
int swaps = 1;
while(swaps)
{
swaps=0;
for(int i = 0;i<N;i++)
{
if(Ar[i]>Ar[i++])
{
swap(Ar[i],Ar[i++]);
swaps = 1;
cost += 6;
}
cost++;
}
}
for(int i=0;i<N;i++)
{
cout<<Ar[i]<<endl;
}
cout<<cost<<endl;
}
void shellSort(int Ar[], int N)
{
cost=0;
int swaps = 1;
int gap = N/2;
while(gap>0)
{
while(swaps)
{
swaps = 0;
for(int i = 0;i<N;i++)
{
if(Ar[i]>Ar[i+gap])
{
swap(Ar[i],Ar[i+gap]);
swaps = 1;
cost+=6;
}
cost++;
}
}
gap=gap/2;
}
for(int i = 0;i<N;i++)
{
cout<<Ar[i]<<endl;
}
cout<<cost<<endl;
}
void quickSort(int Ar[],int left, int right, int N)
{
cost = 0;
int i=left,j=right,tmp;
int pivot = Ar[(left+right)/2];
/*partition*/
while(i<=j)
{
while(Ar[i]<pivot)i++;
while(Ar[j]>pivot)j--;
if(i<=j)
{
tmp=Ar[i];
Ar[i]=Ar[j];
Ar[j]=tmp;
i++;
j--;
cost +=6;
}
cost+=1;
}
/* recursion*/
if(left<j)quickSort(Ar,left,j,N);
if(i<right)quickSort(Ar,i,right,N);
for(int i=0;i<N;i++)
{
cout<<Ar[i]<<endl;
}
cout<<cost<<endl;
}
/*#if _INCLUDE_LEVEL__<1
int main()
{
}
#endif*/
and here is the main file "sorting2.cpp"
#include <iostream>
#include <cstdlib>
#include "sorting.h"
using namespace std;
//void bubble();
//void shellSort();
//void quickSort();
int main()
{
int N = 20;
int Ar[N];
int Ar2[N];
for(int i = 0;i<N;i++)
{
Ar[i] = Ar2[i] = rand()%100;
}
bubble(Ar[],N);
for(int i = 0;i<N;i++)
{
Ar[i] = Ar2[i];
}
shellSort(Ar[],N);
for(int i = 0;i<N;i++)
{
Ar[i] = Ar2[i];
}
quickSort(Ar[],0,19,N);
}
Thanks in advance!
Change
bubble(Ar[],N);
to
bubble(Ar, N);
(and in other similar places as well)
There are also other problems in your code:
Variable-length arrays are not part of C++ standard:
int Ar[N];
int Ar2[N];
You should change int N = 20; to const int N = 20;
This line produces undefined behavior because the order of evaluation of operator arguments is unspecified:
if(Ar[i]>Ar[i++])

<<method name>> was not declared in this scope for a private static method

I saw the thread earlier called " 'name of method' was not declared in this scope", but the answers didn't really help me at all. The method that this is happening for is a private static method. I am attempting to use it within the class, but it won't work. The name of the method is "nthCoeffCatalan". I'm getting the error every time I use it. I don't know if this will help, but I'm using Code::Blocks with wxWidgets and Mingw32 for a compiler.
Here's the .h file:
#ifndef CATALAN_H
#define CATALAN_H
#include <vector>
#include <cstring>
#include <cstdlib>
#include <string>
using namespace std;
class Catalan
{
public:
Catalan(int);
virtual ~Catalan( );
void recursiveRandomGenerator( );
void boltzmannRandomGenerator( );
int rank( );
void unrank(int, int);
void outputBinaryTree( );
void outputDyckPath( );
void outputTriangulation( );
private:
int n;
int catalanObject[];
int max_size;
static int nthCoeffCatalan(int);
};
#endif // CATALAN_H
Here's the .cpp file:
#include <Catalan.h>
#include <math.h>
#include <time.h>
using namespace std;
int catalanObject[] = {};
int n;
int max_size;
Catalan::Catalan(int sz){
n = sz;
//find out the position of the leaf in a tree which is just a node and n-1 right vertices
max_size = 0;
for(int i = 0; i <=n; i++){
max_size += pow(2,i);
}
catalanObject[max_size];
for (int i = 0; i < max_size; i++){
catalanObject[i] = 0;
}
}
Catalan::~Catalan( ){
delete &n;
delete &max_size;
delete catalanObject;
}
void recursiveRandomGenerator( ){
//initialize the random number generator
srand(time(NULL));
int r = n;
int i = 0;
//give the tree a root
catalanObject[i] = 1;
r--;
//decide size of left and right trees
float x = ((float) (rand()%10000))/(10000.0);
int k = -1;
float s = 0;
int a_r = 0;
int b_k = 0;
int c_rk = 0;
//calculate a_r
if (r == 0){
a_r = 1;
}
else{
//calculate [x^r] in B(x)^2
if (r > 1){
for (int j = r/2; j >= 1; j--){
int temp = 0;
if (r%2 == 0 && j == r/2){
temp = nthCoeffCatalan(j);
temp = temp*nthCoeffCatalan(r-j);
}
else{
temp = nthCoeffCatalan(j);
temp = temp*nthCoeffCatalan(r-j);
temp = temp*2;
}
a_r += temp;
}
}
//calculate [x^r] in 2B(x)
a_r += 2*nthCoeffCatalan(r);
}
while (x > s){
k = k + 1;
//calculate b_k
if (k == 0){
b_k = 1;
}
else{
b_k = nthCoeffCatalan(k);
}
//calculate c_rk
if (k == r){
c_rk = 1;
}
else{
c_rk = nthCoeffCatalan(r-k);
}
//re-calculate s
int temp;
temp = (float) b_k;
temp = temp * (float) c_rk;
temp = temp / (float) a_r;
s += temp;
}
}
void boltzmannRandomGenerator( ){
}
int rank( ){
return 0;
}
void unrank(int rnk, int n){
}
void outputBinaryTree( ){
}
void outputDyckPath( ){
}
void outputTriangulation( ){
}
static int nthCoeffCatalan(int n){
int num = 1;
int den = 1;
int retVal = 0;
for(int i = 0; i < n; i++){
num = num*(n+i+1); // runs from n+1 to 2n (=2n!/n!)
den = den*(i+1); // runs from 2 to n (=n!)
}
retVal = num/den;
return retVal;
}
Side Note
Also, as a side note I want to use an array as a class variable but in the constructor, on the line where I initialize the size of the array, my debugger says that the code has no effect. Did I do something wrong?
You are mistakenly providing definitions of global functions, but you actually wanted to define member functions (whose declarations appear in the class definition of Catalan).
So for instance, in your .cpp file:
static int nthCoeffCatalan(int n)
{
// ...
}
Should be:
int Catalan::nthCoeffCatalan(int n)
// ^^^^^^^^^
{
// ...
}
This applies also to other non-static member functions. So for instance (again in your .cpp file) instead of:
void recursiveRandomGenerator( )
{
// ...
}
You should write:
void Catalan::recursiveRandomGenerator( )
// ^^^^^^^^^
{
// ...
}
And so on.
All of your member function definitions should be qualified as belonging to Catalan. So, for example, the definition of recursiveRandomGenerator should actually look like:
void Catalan::recursiveRandomGenerator( ){
// ...
}
Also, you should not put the static keyword before the definition of nthCoeffCatalan. It should look like this:
int Catalan::nthCoeffCatalan(int n){
// ...
}
Your class definition declares a bunch of member functions, including nthCoeffCatalan. In the source file, only two members are defined: the constructor and the destructor. All of the rest of the functions are free functions. You have to mark them as member functions by adding Catalan:: to their names.