Segmentation Core Dump C++, In Constructor - c++

Hello I'm currently trying to make a program for an IsingModel and one of the obstacles is to make a class that holds an array. The array that is held by this class is two dimensional and is full of of either -1 or 1's. Since the length of the array is unknown until the class is created I used a class constructor to make this array. The problem is somewhere in that constructor I must be trying to access memory I cannot since I get a segmentation core dump somewhere in that constructor:
#include <time.h> // So we can use time() function
#include <iostream>
#include <string>
#include<stdlib.h>
using namespace std;
class isingModel {
private:
int length;
int relaxationSteps;
double fieldStrength;
double couplingConstant;
public:
//This is the block that throws the segmentation core dump
isingModel() {
int lattice[length][length];
/*Now let's initialize the lattice */
for (int i=1;i<length;i++){
for (int j=1;j<length;j++){
int randNum = rand() % 2; // Generate a random number between 0 and 1
lattice[i][j]=2*(randNum-.5);
cout << lattice[i][j];
}
}
}
void set_values (int,double,double,int);
int area() {return length*fieldStrength*couplingConstant*relaxationSteps;}
};
void isingModel::set_values (int l, double H,double C,int duration) {
length = l;
fieldStrength = H;
couplingConstant = C;
relaxationSteps = duration;
}
int main () {
int L,duration;
double hConstant,couple;
cout << "Enter the length of the lattice: ";
cin >> L;
cout << "Enter the stength of the field: ";
cin >> hConstant;
cout << "Enter the stength of coupling: ";
cin >> couple;
cout << "Enter the number of times to relax the system: ";
cin >> duration;
isingModel iModel;
iModel.set_values (L,hConstant,couple,duration);
cout << "area: " << iModel.area() << endl;
return 0;
}

You're using length before setting it with set_values().

Related

I'm trying to create a currency conversion program with c++, I don't know how to continue

#include <iostream>
using namespace std;
int Convert(int dollars)
{
int amount = dollars * 113;
cin >> dollars;
}
int main ()
{
Convert ();
count << "Enter the amount you want to convert";
}
There are multiple issues with your program, first it is expecting an argument which you are not supplying, move cin to main and send the input to Convert() function. Then, return the conversion and print it.
#include <iostream>
using namespace std;
int Convert(int dollars)
{
return (dollars * 113);
}
int main ()
{
int amount;
cout << "Enter the amount you want to convert and press enter ";
cin >> amount;
cout << "Result is = " << Convert(amount) << endl;
return 0;
}

Passing dynamic arrays to recieve inputs in separate functions

I would like to pass dynamic arrays to functions and receive user input. Currently I'm using the following code:
#include <iostream>
using namespace std;
struct make
{
int part;
int graph;
int like;
};
int z;
int *p = new int [z];
void inpart( make x[],int *fig)
{
cout << "Input part\n";
cin >> x[*fig].part;
}
void ingraph(make x[],int *tig)
{
cout << "Input graph\n";
cin >> x[*tig].graph;
}
void inlike(make x[],int *gig)
{
cout << "Input like\n";
cin >> x[*gig].like;
}
int main()
{
cout << "Input array count\n";
cin >> z;
make p[z];
for (int i=0; i < z; i++)
{
inpart(p,&z);
ingraph(p,&z);
inlike(p,&z);
}
for (int i=0; i < z; i++)
{
cout << "the result is\n";
cout << p[z].part << ", ";
cout << p[z].graph << ", ";
cout << p[z].like << "\n";
}
}
My input 1,1,1 for all the structure objects should output 1,1,1. However, the answer I receive is 1,0,2. Why?
Firstly, you shouldn't trying to initialize a static buildin array in run-time:
Your implementation is wrong here:
cout<< "Input array count\n";
cin>>z;//initialized in run-time
make p[z]; // wrong, need to be allocated with new
make* example = new make[z]; // Ok!
Secondly, you're trying to read and write out of bounds of the created array. It's Undefined behaviour. When you're creating an array with size N, chunk of the memory will be allocated to which you can have access by index. In your case from 0 to z or [0,z), excluding z. To sum up, your cycle should look like this:
for (int i = 0; i < z; i++) {
inpart(p,&i);
ingraph(p,&i);
inlike(p,&i);
}
Actually u've made a lot of mistakes in your code, but I feel like you will understand this later when continue learning.

declaring "Players" upon user answer. Users choose how many players. Player is a struct

struct Player {
int money=1500;
int position=1;
//Position positionn;
//int number; // number of player
bool eliminated =false;
};
I have this in main:
cout <<"Enter the number of players:";
cin >> numOfPlayers;
//between 2-8 ? how
for (int i=0; i<numOfPlayers; i++)
{
Player player[i];
}
1)how do I store the values from the for loop?
2)How do I put this in a separate function but still have the values passed into main?
You could do something like this:
#include <iostream>
#include <vector>
#include "Player.hpp" // Your header file for Player struct.
int main()
{
std::cout << "Enter player quantity: ";
unsigned int quantity;
std::cin >> quantity;
std::vector<Player> game_players(quantity);
//...
return EXIT_SUCCESS;
}
See constructors for std::vector.
Edit 1 - Dynamic allocation
If you are not allowed to use std::vector or must use arrays, this is one method:
int main()
{
std::cout << "Enter player quantity: ";
unsigned int quantity_of_players;
std::cin >> quantity_of_players;
Player * p_players = new Player[quantity_of_players];
//...
delete [] p_players;
return 0;
}
The above code fragment allocates the container of player in dynamic memory (a.k.a. heap), since the quantity is not known a compile time. The memory is deleted prior to returning back to the operating system.
Edit 2: Passing the players
You would pass the container of Players by using references:
void Print_Player_Info(const std::vector<Player>& players)
{
for (unsigned int i = 0; i < players.size(); ++i)
{
std::cout << "Player " << i << ":\n";
std::cout << " money: " << players[i].money << "\n";
std::cout << "\n";
}
}

Can two class members be used in the same function? (classes and objects) (C++)

I am new to programming and I have started with C++. At this point I am experimenting with classes and objects.
My problem is that I am not able to get the correct result in what I want.
Here is my code:
#include <iostream>
using namespace std;
class Variable
{
public:
int classAnum;
int classBnum;
void sumVar(){
cout << classAnum + classBnum <<endl;
}
};
int main()
{
Variable numA;
Variable numB;
cout << "Enter a number: ";
cin >> numA.classAnum;
cout << "Enter another number: ";
cin >> numB.classBnum;
numA,numB.sumVar();
return 0;
}
The output that I am being given is:
Enter a number: (any number)
Enrer another number: (any number)
1955294086
I get this output with any number I enter.
But if I use this code:
#include <iostream>
using namespace std;
class Variable
{
public:
int classAnum;
int classBnum;
void sumVar(){
cout << classAnum + classBnum <<endl;
}
};
int main()
{
Variable numA;
Variable numB;
cout << "Enter a number: ";
cin >> numA.classAnum;
cout << "Enter another number: ";
cin >> numB.classBnum;
cout << numA.classAnum + numB.classBnum;
return 0;
}
I get a correct result. Can someone explain me if I am able to use two objects in the same function? And if I can, how should it be?
If you'd like to input two numbers into Variable class instance and then call the function sumVar() to print the sum of the two numbers, you can do this:
#include <iostream>
using namespace std;
class Variable
{
public:
int classAnum;
int classBnum;
void sumVar(){
cout << classAnum + classBnum <<endl;
}
};
int main()
{
Variable num;
cout << "Enter a number: ";
cin >> num.classAnum;
cout << "Enter another number: ";
cin >> num.classBnum;
num.sumVar();
return 0;
}
Seeing your code, it looks like you want to find the sum of two numbers which are members of your class. you don't need to instantiate 2 objects for that, you can accomplish it by instantiating only one object, and initialize the properties this way:
#include <iostream>
using namespace std;
class Variable
{
public:
int number1;
int number2;
void sumVar(){
cout << number1 + number2 <<endl;
}
};
int main()
{
Variable object;
cout << "Enter a number: ";
cin >> object.number1;
cout << "Enter another number: ";
cin >> object.number2;
object.sumVar();
return 0;
}
This way you can easily sum up members of your class.
in the future, if you want to add two objects of your own classes, you may need to use operator overloading concept that you can find on several tutorial online.
Good Luck !

Segmentation fault using string pointer

I'm a C++ newbie, I'm trying to put in practice pointers with strings. The program I have made is just to store strings the user types in the command line. But I'm getting segfault, not sure why.
This is the code:
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
//This code is meant to learn how to use pointers and strings
//Ask the user for who are they in the family and save it in string array!
void print_string (string* Value, int const nSize);
int get_names(string* Family_input);
int main ( int nNumberofArgs, char* pszArgs[])
{
cout << "Tis program stores your family members\n";
cout<< "Type the names and write 0 to exit\n";
string familia_string;
string* familia = &familia_string;
int family_number;
family_number=get_names(familia);
cout << "The family members are: ";
print_string(familia, family_number);
cout << endl;
return 0;
}
int get_names(string* Family_input)
{
int i=0;
string input="";
string old_input="";
while (input!="0")
{
cout << "type " << i <<" member\n";
//cin >> *(Family_input+i);
//input=*(Family_input+i);
cin >> input;
*(Family_input + old_input.length()) = input;
old_input=input;
i++;
}
return i;
}
void print_string (string* Value, int const nSize)
{// I don't want to &psValue to be changed!
for (int i=0; i<nSize; i++)
{
cout << *(Value+i) << " ";
//&psValue++;
}
}
I'm not sure if it's because I'm not taking correctly the size of the string, or I'm not using correctly the pointer or is that I have to allocate memory before using the offset.
As #kleszcz pointed out already, the line
*(Family_input + old_input.length()) = input;
is wrong. You are accessing memory that you are not supposed to.
The easiest fix is to change get_names slightly:
int get_names(string* Family_input)
{
int i=0;
string input="";
while (input!="0")
{
cout << "type " << i <<" member\n";
cin >> input;
*Family_input += input; // Just keep on appending to the input argument.
*Family_input += "\n"; // Add a newline to separate the inputs.
i++;
}
return i;
}
Also change print_string to:
void print_string (string* Value)
{
cout << *Value;
}
Of course, print_string has become so simple, you don't need to have it at all.
You could change get_names to use a reference argument instead of a pointer argument. This is a better practice.
int get_names(string& Family_input)
{
int i=0;
string input="";
while (input!="0")
{
cout << "type " << i <<" member\n";
cin >> input;
Family_input += input; // Just keep on appending to the input argument.
Family_input += "\n"; // Add a newline to separate the inputs.
i++;
}
return i;
}
Then, change the call to get_names. Instead of using
family_number=get_names(familia);
use
family_number=get_names(familia_string);
You get seg fault because you haven't allocate memory for an array of strings.
*(Family_input + old_input.length()) = input;
This is total nonsense. If you'd have an array you increment index only by one not by length of string.
If you want to save different names in different string objects I would suggest:
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
void print_string(string** Value, int const nSize);
void get_names(string** Family_input, int count);
int main(int nNumberofArgs, char* pszArgs[]) {
cout << "This program stores your family members\n";
int family_number;
cout << "Types the number of family members";
cin >> family_number;
/*allocate the number of string pointers that you need*/
string** familia = new string*[family_number];
cout << "Type the names\n";
get_names(familia, family_number);
cout << "The family members are: ";
print_string(familia, family_number);
cout << endl;
return 0;
}
void get_names(string** Family_input, int count) {
for(int i = 0 ; i < count; i++){
cout << "type " << i << " member\n";
/*create a string obj in the heap memory*/
string *input = new string ("");
// using that way you get only a single word
cin >> *input;
/*create a string object on the stack and put its pointer in the family_array*/
Family_input[i] = input;
}
}
void print_string(string** Value, int const nSize) {
for (int i = 0; i < nSize; i++) {
cout << *(Value[i]) << " ";
}
}