Program Crashes While Setting Data in Array - c++

I'm working on a project and every time I go to set example[4].m_dArray[3], the program crashes. I can set the value of every other variable up until I get to example[4].m_dArray[3]. Any help would be appreciated!
Prog1Class.h:
#include "Prog1Struct.h"
#pragma once
#include <iostream>
#include <string.h>
using namespace std;
class Prog1Class
{
private:
Prog1Struct example[4];
public:
Prog1Class();
~Prog1Class ();
void setStructData();
void getStructData();
void ptrFunction();
void refFunction();
void printStruct();
void printData();
};
Prog1Struct.h:
#pragma once
#include <string.h>
struct Prog1Struct {
int m_iVal;
double m_dArray[4];
char m_sLine[80];
};
Prog1Class.cpp:
#include "Prog1Class.h"
#include "Prog1Struct.h"
#include <iostream>
#include <string.h>
using namespace std;
Prog1Class::Prog1Class()
{
}
Prog1Class::~Prog1Class()
{
delete &example[4];
}
int main()
{
Prog1Class *aClass = new Prog1Class();
aClass->setStructData();
aClass->printData();
return 0;
}
void Prog1Class::setStructData()
{
for(int i=0;i<5;i++)
{
cout << "Enter an integer: ";
cin >> example[i].m_iVal;
for(int j=0;j<5;j++)
{
cout << endl << "Enter a double: ";
cin >> example[i].m_dArray[j];
}
cout << endl << "Enter a string: ";
cin.ignore(256,'\n');
cin.getline(example[i].m_sLine, 80, '\n');
cout << endl;
}
}
void Prog1Class::getStructData()
{
}
void Prog1Class::printData()
{
for(int i=0;i<5;i++)
{
cout << example[i].m_iVal;
for(int j=0;j<5;j++)
{
cout << example[i].m_dArray[j];
}
cout << example[i].m_sLine;
}
}

You need to change this
class Prog1Class
{
private:
Prog1Struct example[4];
to this
class Prog1Class
{
private:
Prog1Struct example[5];
In C++ arrays start at index 0, so an array of size 4 has valid indexes 0 upto 3. You're using example[4] so you need an array of (at least) size 5.
You also need to remove delete &example[4]; from your destructor as well.

First , delete &example[4]; should be delete [] example;
Second, where did you allocate memory for example?

You need to show the way the example object is declared? I'd suspect some mis-allocated or mis-declared problem with it. Your setStructureData doesn't do anything ostensibly wrong (assuming the array sizes match and the size of the string is fitting - it is a char array, not a pointer, correct?).

for (int i = 0; i < 5; i++)
// ^^^^^
Your for loops should have an ending condition with i < 4 since your arrays have only 4 spaces. Moreover, your delete should be delete[] example;.

Array deletion is delete [] example, not your way. Also, to use delete data needs to be allocated with new
Here is small example how to use new and delete
#include <iostream>
struct foo
{
foo() {std::cout <<"constructed\n";}
~foo() {std::cout <<"destroyed\n";}
};
int main ()
{
foo * pt;
pt = new foo[3];
delete[] pt;
return 0;
}
Also the output:
constructed
constructed
constructed
destroyed
destroyed
destroyed
I gave a lesson about new/delete and just now seen real problem:
example[4] is out of bounds. If you declare array with 4 elements it means you have indexes 0, 1, 2, 3 and nothing more.

Related

Code exiting when Dynamic Array of class allocated

I am trying to dynamically allocate an array and whenever it gets to the part where it dynamically allocates the program exits. I would rather not use vectors as I am trying to learn how to do this using dynamic arrays.
This is the simplified code:
#include <iostream>
#include <string>
using namespace std;
class Student
{
private:
double calcAverage(double* testArray);
char calcGrade(double average);
public:
int nTests, sameTests, idNum;
string name;
double average, *testArray;
char grade;
};
int i;
Student fillStudentArray(int nStudents);
int main()
{
*studentArray = fillStudentArray(nStudents);
return 0;
}
Student fillStudentArray(int nStudents)
{
Student *newStudentArray = new Student[nStudents];
cout << "If you can see this I worked. ";
delete[] studentArray;
return *newStudentArray;
}
I have tried the solution posted here Creation of Dynamic Array of Dynamic Objects in C++ but it also exits in a similar way. The main for the code looks like this.
int main()
{
int nStudents = 3; //this number is just for testing, in actual code it has user input
Student** studentArray = new Student*[nStudents];
cout << "1 ";
for(i = 0; i < nStudents; i++)
{
cout << "2 ";
studentArray[i] = new Student[25];
cout << "3 ";
}
return 0;
}
close (heres a cigar anyway)
Student* fillStudentArray(int nStudents); <<== function must return pointer to students
int main()
{
int nStudents = 3; <<<=== declared nstudents
Student *studentArray = fillStudentArray(nStudents); <<< declare studentArray
return 0;
}
Student *fillStudentArray(int nStudents) <<<== return pointer
{
Student* newStudentArray = new Student[nStudents];
cout << "If you can see this I worked. ";
// delete[] studentArray; <<<== what were you trying to delete?
return newStudentArray; <<<=== return pointer
}
the second code you showed is not relevant, its creating a 2d array

C++: Setters and Getters for Arrays

I am struggling to find the correct format for initializing a (private) array within a class and getting/setting the values from outside the class.
My code is semi-functional, but feels awkward in incorrectly formatted.
It is returning only the first element of the array, I want it to return all the contents. Read code comments for additional details.
Note: This is (a very small part of) a project I am working on for school -- an array must be used, not a vector or list.
student.h
class Student {
public:
// Upon researching my issue, I read suggestions on passing pointers for arrays:
void SetDaysToCompleteCourse(int* daysToCompleteCourse[3]);
int* GetDaysToCompleteCourse(); // Ditto # above comment.
private:
int daysToCompleteCourse[3];
student.cpp
#include "student.h"
void Student::SetDaysToCompleteCourse(int* daysToCompleteCourse) {
// this->daysToCompleteCourse = daysToCompleteCourse; returns error (expression must be a modifiable lvalue)
// Feels wrong, probably is wrong:
this->daysToCompleteCourse[0] = daysToCompleteCourse[0];
this->daysToCompleteCourse[1] = daysToCompleteCourse[1];
this->daysToCompleteCourse[2] = daysToCompleteCourse[2];
}
int* Student::GetDaysToCompleteCourse() {
return daysToCompleteCourse;
}
ConsoleApplication1.cpp
#include "pch.h"
#include <iostream>
#include "student.h"
int main()
{
Student student;
int daysToCompleteCourse[3] = { 1, 2, 3 };
int* ptr = daysToCompleteCourse;
student.SetDaysToCompleteCourse(ptr);
std::cout << *student.GetDaysToCompleteCourse(); // returns first element of the array (1).
}
I gave this my best shot, but I think I need a nudge in the right direction.
Any tips here would be greatly appreciated.
I would say:
// student.h
class Student
{
public:
// If you can, don't use numbers:
// you have a 3 on the variable,
// a 3 on the function, etc.
// Use a #define on C or a static const on C++
static const int SIZE= 3;
// You can also use it outside the class as Student::SIZE
public:
void SetDaysToCompleteCourse(int* daysToCompleteCourse);
// The consts are for "correctness"
// const int* means "don't modify this data" (you have a setter for that)
// the second const means: this function doesn't modify the student
// whithout the const, student.GetDaysToCompleteCourse()[100]= 1 is
// "legal" C++ to the eyes of the compiler
const int* GetDaysToCompleteCourse() const; // Ditto # above comment.
Student()
{
// Always initialize variables
for (int i= 0; i < SIZE; i++) {
daysToCompleteCourse[i]= 0;
}
}
private:
int daysToCompleteCourse[SIZE];
// On GCC, you can do
//int daysToCompleteCourse[SIZE]{};
// Which will allow you not to specify it on the constructor
};
// student.cpp
void Student::SetDaysToCompleteCourse(int* newDaysToCompleteCourse)
{
// It's not wrong, just that
// this->daysToCompleteCourse[0] = daysToCompleteCourse[0];
// use another name like newDaysToCompleteCourse and then you can suppress this->
// And use a for loop
for (int i= 0; i < SIZE; i++) {
daysToCompleteCourse[i]= newDaysToCompleteCourse[i];
}
}
const int* Student::GetDaysToCompleteCourse() const
{
return daysToCompleteCourse;
}
// main.cpp
#include <iostream>
std::ostream& operator<<(std::ostream& stream, const Student& student)
{
const int* toShow= student.GetDaysToCompleteCourse();
for (int i= 0; i < Student::SIZE; i++) {
stream << toShow[i] << ' ';
}
return stream;
}
int main()
{
Student student;
int daysToCompleteCourse[3] = { 1, 2, 3 };
// You don't need this
//int* ptr = daysToCompleteCourse;
//student.SetDaysToCompleteCourse(ptr);
//You can just do:
student.SetDaysToCompleteCourse(daysToCompleteCourse);
// On C++ int* is "a pointer to an int"
// It doesn't specify how many of them
// Arrays are represented just by the pointer to the first element
// It's the FASTEST and CHEAPEST way... but you need the SIZE
const int* toShow= student.GetDaysToCompleteCourse();
for (int i= 0; i < Student::SIZE; i++) {
std::cout << toShow[i] << ' ';
// Also works:
//std::cout << student.GetDaysToCompleteCourse()[i] << ' ';
}
std::cout << std::endl;
// Or you can do: (because we defined operator<< for a ostream and a Student)
std::cout << student << std::endl;
}
You can check out it live here: https://ideone.com/DeJ2Nt

C++, Weird behavior of cout when trying to print integers

Im trying to write a class that stores an id and a value in an container class.
Im using an nested class as my data structure.
When im compiling the code sometimes it prints perfectly, sometimes it prints nothing and sometimes it prints half of the data then stops.
When i debug the code the same weird behavior occours, when it fails during debug it throws an error "Map.exe has triggered a breakpoint.", the Error occours in the print method when im using cout.
cmap.h
#pragma once
class CMap
{
public:
CMap();
~CMap();
CMap& Add(int id, int value);
void print() const;
private:
class container
{
public:
~container();
int container_id = 0;
int container_value = 0;
};
container* p_komp_;
int dim_ = -1;
void resize();
};
cmap.cpp
#include "cmap.h"
#include <iostream>
using namespace std;
CMap::CMap()
{
p_komp_ = new container[0];
}
CMap::~CMap()
{
p_komp_ = nullptr;
cout << "destroy cmap";
}
CMap& CMap::Add(int id, int value)
{
resize();
p_komp_[dim_].container_id = id;
p_komp_[dim_].container_value = value;
return *this;
}
void CMap::resize()
{
container* temp_array = new container[++dim_];
if (dim_ == 0)
{
temp_array[0].container_id = p_komp_[0].container_id;
temp_array[0].container_value = p_komp_[0].container_value;
}
for (unsigned i = 0; i < dim_; i++)
{
temp_array[i].container_id = p_komp_[i].container_id;
temp_array[i].container_value = p_komp_[i].container_value;
}
p_komp_ = temp_array;
}
void CMap::print() const
{
for (unsigned i = 0; i <= dim_; i++)
{
cout << p_komp_[i].container_id;
cout << p_komp_[i].container_value;
}
}
CMap::container::~container()
{
cout << "destruct container";
}
Map.cpp
#include "cmap.h"
#include <iostream>
using namespace std;
void main(void)
{
CMap m2;
m2.Add(1, 7);
m2.Add(3, 5);
m2.print();
}
These two things are a possible reason for your problem:
int dim_ = -1;
and
container* temp_array = new container[++dim_];
When you allocate, you increase dim_ from -1 to 0. That is you create a zero-sized "array", where every indexing into it will be out of bounds and lead to undefined behavior.
You also have memory leaks since you never delete[] what you new[]. I didn't look for more problems, but there probably a more.
And an "array" (created at compile-time or through new[]) will have indexes from 0 to size - 1 (inclusive). You seem to think that the "size" you provide is the top index. It's not, it's the number of elements.
It seems to me that you might need to take a few steps back, get a couple of good books to read, and almost start over.

C++ Dynamic Array: A value of type "void" cannot be used to initialize an entity of type "int"

I am working on a C++ project for school in which the program will read in a list of numbers from a text file, store them in a dynamic array, then print them out to another text file. To be honest I'm a little lost with the pointers in this, and I am getting the error "A value of type "void" cannot be used to initialize an entity of type "int"" in my main source file.
Main.cpp (this is where I'm getting the error):
#include "dynamic.h"
int main
{
readDynamicData("input.txt","output.txt");
}
dynamic.cpp (the skeleton for the program):
#include "dynamic.h"
void readDynamicData(string input, string output)
{
DynamicArray da; //struct in the header file
da.count = 0;
da.size = 5; //initial array size of 5
int *temp = da.theArray;
da.theArray = new int[da.size];
ifstream in(input);
ofstream out(output);
in >> da.number; //prime read
while (!in.fail())
{
if (da.count < da.size)
{
da.theArray[da.count] = da.number;
da.count++;
in >> da.number; //reprime
}
else grow; //if there are more numbers than the array size, grow the array
}
out << "Size: " << da.size << endl;
out << "Count: " << da.count << endl;
out << "Data:" << endl;
for (int i = 0; i < da.size; i++)
out << da.theArray[i];
in.close();
out.close();
delete[] temp;
}
void grow(DynamicArray &da) //this portion was given to us
{
int *temp = da.theArray;
da.theArray = new int[da.size * 2];
for (int i = 0; i<da.size; i++)
da.theArray[i] = temp[i];
delete[] temp;
da.size = da.size * 2;
}
and dynamic.h, the header file:
#include <iostream>
#include <string>
#include <fstream>
#ifndef _DynamicArray_
#define _DynamicArray_
using namespace std;
void readDynamicData(string input, string output);
struct DynamicArray
{
int *theArray;
int count;
int size;
int number;
};
void grow(DynamicArray &da);
#endif
you have to add parenthesis to main or any function:
int main(){/*your code here ...*/};
2- you are using an unitialized objct:
DynamicArray da; //struct in the header file
da.count = 0;
da.size = 5; //initial array size of 5
so int* theArray is a member data and is uninitialized so welcome to a segfault
all the members of da are not initialized so you have to do before using it.
3- also you add parenthesis to grow function:
else grow(/*some parameter here*/); // grow is a function
4- using namespace std; in a header file is a very bad practice.
tip use it inside source
5- why making inclusion of iostream and string.. before the inclusion guard??
correct it to:
#ifndef _DynamicArray_
#define _DynamicArray_
#include <iostream>
#include <string>
#include <fstream>
/*your code here*/
#endif
main is a function so it needs brackets:
int main(){
// your code
return 0; // because it should return intiger
}
And. Your grow is also a function, so if you want to call it you write grow() and it needs DynamicArray as a parameter.
It is impossible to write working programs on C/C++ any programming language not knowing a basic syntax.

Newbie - matrix addition implementation in c++

Hello i'm trying to program the addition of 2 matrices into a new one (and it does when i run the program step by step) but for some reason VS 2010 gives me an access error after it does the addition.
Here is the code.
#include <iostream>
#include <cstdio>
#include <conio>
using namespace std;
class operatii
{
typedef double mat[5][5];
mat ms,m1,m2;
int x1,x2,y1,y2;
public:
void preg();
int cit_val();
void cit_mat(int&,int&,double[5][5]);
void suma();
void afisare(int&,int&,double[5][5]);
};
void operatii::preg()
{
cit_mat(x1,y1,m1);
cit_mat(x2,y2,m2);
suma();
afisare(x1,y1,ms);
}
int operatii::cit_val()
{
int n;
cin>>n;
return n;
}
void operatii::cit_mat(int& x,int& y,double m[5][5])
{
char r;
cout<<"Matrice patratica? Y/N ";
cin>>r;
if ((r=='y')||(r=='Y'))
{
cout<<"Numar linii si coloane: ";
x=cit_val();
y=x;
}
else
{
cout<<"Numar linii: ";
x=cit_val();
cout<<"Numar coloane: ";
y=cit_val();
}
for (int i=1;i<=x;i++)
for (int j=1;j<=y;j++)
cin>>m[i][j];
}
void operatii::suma()
{
if ((x1==x2)&&(y1==y2))
for (int i=1;i<=x1;i++)
for (int j=1;i<=y1;j++)
ms[i][j]=m1[i][j]+m2[i][j];
else cout<<"Eroare";
}
void operatii::afisare(int& x,int& y,double m[5][5])
{
cout<<endl;
for (int i=1;i<=x;i++)
{
for (int j=1;j<=y;j++)
cout<<m[i][j];
cout<<endl;
}
}
void main()
{
operatii matrice;
matrice.preg();
system("PAUSE");
}
Any kind of help would be apreciated.
Arrays are 0-based in c++.
Change your various variants of for (somevar=1; somevar<=something) to for (somevar=0; somevar<something)
You're writing past the end of your arrays, which overwrites stack return address, leading to a return to nonexecutable code, again leading to an access violation.
Also,
for (int j=1;i<=y1;j++)
I think you want to use j not i here. Such errors are much easier to see if you use longer and more distinct variable names than "i" and "j", such as e.g. "Line" and "Column"