I want to declare two dimensional array with variable size.
I wrote the following code but something goes wrong!
int **p2DArray;
p2DArray = new int*[target_counter_new];
for (int i = 0; i < target_counter_new; ++i)
{
p2DArray[i] = new int[target_counter_old];
}
for(int i_oghli=0;i_oghli<target_counter_new;i_oghli++)
for(int j_oghli=0;j_oghli<target_counter_old;j_oghli++)
{
p2DArray[i_oghli][j_oghli]=i_oghli+10;
cout<<p2DArray[i_oghli][j_oghli];
}
what is problem here ?
#include <iostream>
using namespace std;
const int target_counter_new = 4;
const int target_counter_old = 4;
int main() {
int **p2DArray;
p2DArray = new int*[target_counter_new];
for (int i = 0; i < target_counter_new; ++i) {
p2DArray[i] = new int[target_counter_old];
}
for(int i_oghli=0;i_oghli<target_counter_new;i_oghli++) {
for(int j_oghli=0;j_oghli<target_counter_old;j_oghli++) {
p2DArray[i_oghli][j_oghli]=i_oghli+10;
cout<<p2DArray[i_oghli][j_oghli] << " ";
}
cout << endl;
}
// don't forget to delete the array
for (int i = 0 ; i < target_counter_new; ++i) {
delete [] p2DArray[i];
}
delete [] p2DArray;
return 0;
}
Check here : code
There doesn't appear to be any problem.
Related
My program is about taking the transpose of a matrix and displaying it, using structs. I'm using pointer to structs in each function, just for practice although I could've done it by simply passing the struct or by reference. The program is working fine until function inputMatrix. The program takes input and then finishes executing without any output.
What I know for sure is the problem is in display function or structure trans I'm creating in main(which has the final result).
My code is below:
#include <iostream>
#include <iomanip>
using namespace std;
struct Matrix
{
int **data;
int rows;
int columns;
};
void createMatrix(Matrix *mat)
{
mat->data = new int *[mat->rows];
for (int i = 0; i < mat->columns; i++)
{
mat->data[i] = new int[mat->columns];
}
}
void inputMatrix(Matrix *mat)
{
for (int i = 0; i < mat->rows; i++)
{
for (int j = 0; j < mat->columns; j++)
{
cout << "Enter element of row " << i + 1 << " and column " << j + 1<<endl;
cin >> mat->data[i][j];
}
}
}
Matrix transpose(Matrix* mat)
{
Matrix transpose;
transpose.rows = mat->rows;
transpose.columns = mat->columns;
for (int i = 0; i < mat->rows;i++)
{
for(int j = 0;j<mat->columns;j++)
{
transpose.data[i][j] = mat->data[j][i];
}
}
return transpose;
}
void display(Matrix* mat)
{
for(int i = 0;i<mat->rows;i++)
{
for(int j = 0;j<mat->columns;j++)
{
cout<<setw(3)<<mat->data[i][j];
}
cout<<endl;
}
}
int main()
{
Matrix mat;
cout<<"Enter the rows of matrix: \n";
cin>>mat.rows;
cout<<"\nEnter the columns of matrix: \n";
cin>>mat.columns;
createMatrix(&mat);
inputMatrix(&mat);
cout<<endl;
Matrix trans = transpose(&mat);
display(&trans);
return 0;
}
The problem was in function transpose, I needed to allocate memory to Matrix transpose
The code is below:
Matrix transpose(Matrix* mat)
{
Matrix transpose;
transpose.rows = mat->rows;
transpose.columns = mat->columns;
createMatrix(&transpose);
for (int i = 0; i < mat->columns;i++)
{
for(int j = 0;j<mat->rows;j++)
{
transpose.data[i][j] = mat->data[j][i];
}
}
return transpose;
}
Can someone explain me why when i back form function i lost my data from tabOfOffsets. I did the same thing twice and program crash only with the second array.
I printed values of this array on the end of function and everything is clear and correct. Maybe i make mistake somewhere with delete?
Below it is the code.
#include<iostream>
#include <algorithm>
using std::cout;
using std::endl;
void changeSizeOfVector(int *tabValue, int *tabOffsets, int &oldSize, int
newSize) {
int temp = std::min(oldSize, newSize);
int *newTabOfValues = new int [newSize] {0};
int *newTabOfOffsets = new int [newSize] {0};
for (int i = 0; i < temp; i++) {
newTabOfValues[i] = tabValue[i];
newTabOfOffsets[i] = tabOffsets[i];
}
delete[] tabValue;
delete[] tabOffsets;
tabValue = new int [newSize] {0};
tabOffsets = new int [newSize] {0};
for (int i = 0; i < newSize; i++) {
tabValue[i] = newTabOfValues[i];
tabOffsets[i] = newTabOfOffsets[i];
std::cout << tabOffsets[i] << tabValue[i] << endl;
}
oldSize = newSize;
delete[] newTabOfValues;
delete[] newTabOfOffsets;
for (int i = 0; i < newSize; i++) {
std::cout << tabOffsets[i] << tabValue[i] << endl;
}
}
int main() {
int SIZE = 10;
int * tabOfOffsets = new int[SIZE];
int * tabOfValues = new int[SIZE];
for (int i = 0; i < SIZE; i++)
{
tabOfValues[i] = i;
tabOfOffsets[i] = i;
cout << tabOfValues[i] << " : " << tabOfOffsets[i] << endl;
}
changeSizeOfVector(tabOfValues, tabOfOffsets, SIZE, 12);
for (int i = 0; i < SIZE; i++) {
cout << tabOfOffsets[i] << " : " << tabOfValues[i] << endl;
}
delete[] tabOfOffsets;
delete[] tabOfValues;
}
This function declaration is wrong:
void changeSizeOfVector(int *tabValue, int *tabOffsets, int &oldSize, int
newSize);
it means you can change the values of tabOffsets but not the pointer itself in order to make it behave correctly you should declare it as follows:
void changeSizeOfVector(int *tabValue, int **tabOffsets, int &oldSize, int
newSize);
This way you can change the pointer itself and assign a newly allocated array to it.
I am making conway's game of life. I have two classes, one for the plane of cells, and another for the cells. The cells are like a 2d linked list with 4 pointers per cell pointing to the vertical and horizontal neighbors. When trying to access any of the cell pointers to other cells, or the alive member the program crashes.
my code
//game.h
#ifndef GAME_H_
#define GAME_H_
#include <iostream>
class cell{
public:
bool alive;
cell* top;
cell* bot;
cell* lef;
cell* rig;
cell(){
alive = false;
top = bot = lef = rig = nullptr;
}
cell* link(char);
int alive_neighbors();
void link_right(cell*);
void link_down(cell*);
void refresh_cell();
};
class field{
public:
int size;
cell * origin;
bool ** new_state;
cell *** fi;
field(int a);
~field();
};
#endif
and
//game.cpp
#include <iostream>
#include "game.h"
int cell::alive_neighbors(){
int num = 0;
(this->top)?((this->top->alive)?(++num):(num)||((this->top->rig)?((this->top->rig->alive)?(num++):(num)):(num))):(num);
(this->bot)?((this->bot->alive)?(++num):(num)||((this->bot->lef)?((this->bot->lef->alive)?(num++):(num)):(num))):(num);
(this->rig)?((this->rig->alive)?(++num):(num)||((this->rig->bot)?((this->rig->bot->alive)?(num++):(num)):(num))):(num);
(this->lef)?((this->lef->alive)?(++num):(num)||((this->lef->bot)?((this->lef->bot->alive)?(num++):(num)):(num))):(num);
return num;
}
void cell::link_right(cell* linkee){
this->rig = linkee;
linkee->lef = this;
}
void cell::link_down(cell* linkee){
this->bot = linkee;
linkee->top = this;
}
field::field(int a){
size = a;
for (int i= 0; i < size; i++){
fi[i] = new cell*[size];
for (int j = 0; j < size; j++){
fi[i][j] = new cell;
}
}
for (int i = 0; i < size; i++){
for (int j = 0; j < size -1; j++){
this->fi[i][j]->link_right(this->fi[i][j+1]);
this->fi[j][i]->link_down(this->fi[j+1][i]);
}
}
origin = fi[0][0]
}
field::~field(){
for (int i = size -1; i >= 0; i--){
for (int j = size -1;j >= 0; j--){
delete fi[i][j];
}
delete fi[i];
}
}
Error:
#include "game.h"
int main(){
field game(10);
std::cout << game.origin->alive << std::endl; //compiles but crashes :(
std::cout << game.origin->rig << std::endl; //also compiles and crashes without giving adress.
std::cout << game.fi[0][0]->alive; //even directly accessing the cell compiles and crashes.
}
The problem was with game.cpp try this code
//game.cpp
#include <iostream>
#include "stackoverflow.hpp"
int cell::alive_neighbors(){
int num = 0;
(this->top)?((this->top->alive)?(++num):(num)||((this->top->rig)?((this->top->rig->alive)?(num++):(num)):(num))):(num);
(this->bot)?((this->bot->alive)?(++num):(num)||((this->bot->lef)?((this->bot->lef->alive)?(num++):(num)):(num))):(num);
(this->rig)?((this->rig->alive)?(++num):(num)||((this->rig->bot)?((this->rig->bot->alive)?(num++):(num)):(num))):(num);
(this->lef)?((this->lef->alive)?(++num):(num)||((this->lef->bot)?((this->lef->bot->alive)?(num++):(num)):(num))):(num);
return num;
}
void cell::link_right(cell* linkee){
this->rig = linkee;
linkee->lef = this;
}
void cell::link_down(cell* linkee){
this->bot = linkee;
linkee->top = this;
}
field::field(int a){
size = a;
fi = new cell**[size];
for (int i= 0; i < size; i++){
fi[i] = new cell*[size];
for (int j = 0; j < size; j++){
fi[i][j] = new cell;
}
}
for (int i = 0; i < size; i++){
for (int j = 0; j < size -1; j++){
this->fi[i][j]->link_right(this->fi[i][j+1]);
this->fi[j][i]->link_down(this->fi[j+1][i]);
}
}
origin = fi[0][0];
}
field::~field(){
for (int i = size -1; i >= 0; i--){
for (int j = size -1;j >= 0; j--){
delete fi[i][j];
}
delete fi[i];
}
}
I do not understand why people here tend to get annoyed because the ones asking questions are not coding with the "correct" style. We all need to make mistakes and learn from them. On that note in the future when you work on another C++ project. Try using the STL containers, they will be refreshingly simple and efficient. You'll love them.
Also think of n-dimensional arrays this way. Use one * for every dimension. So an int* arr is a 1-D array and an int** arr is a 2-D array. You can switch to a cell** here since you want a 2-D array :)
I am currently creating a program that simulates a Galton board in C++. I understand how to create a pointer, create an array of pointers, and point each one at another array of ints. My problem is occuring when i try to descruct my pointer array, its telling me:
"Debug Error!
HEAP CORRUPTION DETECTED: after Normal block (#927) at 0x0115E978.
CRT detected that the application wrote to memory after end of heap buffer."
I've been banging my head against the wall with this one, as it seems all the examples I can find online have this exact approach. I even rewrote my program into a class to make it more simple. The program runs and does exactly what it's supposed to until the ob1 starts to descruct, which is when the program pukes. I'm stuck.
Here is my code:
#include <iostream>
#include <string>
#include <algorithm>
#include <iomanip>
#include <cstdlib>
#include <ctime>
using namespace std;
class foo
{
public:
foo();
foo(int);
~foo();
void allocateSpace();
void runGame();
void printResults();
private:
int bins;
int** p;
};
foo::foo()
{
this->bins = 0;
}
foo::foo(int bins)
{
this->bins = bins;
this->p = new int*[bins]; //setting p to array of pointers
}
foo::~foo()
{
for (int i = 0; i < bins; i++)
{
delete[] this->p[i];
}
delete[] p;
}
void foo::allocateSpace()
{
for (int i = 0; i < bins; i++)
{
this->p[i] = new int[i]; //creatung an int array of size i at each pointer array cell
for (int j = 0; j <= i; j++)
{
this->p[i][j] = 0;
}
}
}
void foo::runGame()
{
const int numOfRuns = 1000;
for (int i = 0; i < numOfRuns; i++)
{
this->p[0][0]++; //each ball hits the first peg, so always increment it before anything else
int j = 0; //setting j = 0 sets it to the left
for (int i = 1; i < bins; i++)
{
int rando = rand() % 2;
if (rando == 1) //move right
{
j++;
}
this->p[i][j]++;
}
}
}
void foo::printResults()
{
for (int i = 0; i < bins; i++)
{
for (int j = 0; j <= i; j++)
{
cout << setw(5) << this->p[i][j];
}
cout << endl;
}
}
int main()
{
srand(time(0));
int numOfBins;
cout << "Enter the number of bins: ";
cin >> numOfBins;
cout << endl;
foo ob1(numOfBins);
for (int i = 0; i < 50; i++)
{
ob1.allocateSpace();
ob1.runGame();
ob1.printResults();
}
system("pause");
return 0;
}
Any help would be much appreciated.
In allocateSpace, you write beyond the allocated object. This corrupts your heap.
this->p[i] = new int[i];
for (int j = 0; j <= i; j++)
{
this->p[i][j] = 0;
}
printResults has a similar problem: You read beyond the allocated object.
Then, in runGame, you attempt to increment a 0 sized object.
this->p[0][0]++;
The fix:
It seems you need to increase your allocation by 1.
this->p[i] = new int[i+1];
This will avoid the heap corruption issue. You still have a memory leak issue, because you allocate new memory on top of your existing memory on each iteration in main().
Your code would be safer if you adopted the use of vector<> instead of managing dynamically allocated arrays.
I keep getting the error in VS 2100 "CRT detected that the application wrote to memory before start of heap buffer"
Can anyone help? My int Main is all the way on the bottom. The error occur when the delete [] command is run on the operator= function
#include "intset.h"
const int MAXINITIALSIZE = 5;
int IntSet::numOfArray = 0;
IntSet::IntSet(int a, int b, int c, int d, int e)
{
numOfArray++;
int tempArray[] = {a, b, c, d, e};
size = determineHighest(tempArray) + 1; //determines largest int
cout << "size is " << size << endl;
arrayPtr = new bool[size]; //creates array of bool
for (int i = 0; i < size; i++) //fill bool array
{
arrayPtr[i]= false; //arrayptr is a bool pointer created in the header
}
for (int i = 0; i < MAXINITIALSIZE; i++)
{
arrayPtr[tempArray[i]]= true;
}
for (int i = 0; i < size; i++)
{
cout << &arrayPtr[i] << endl;
}
}
IntSet::IntSet(const IntSet &intsetObject)
{
numOfArray++;
size = intsetObject.size;
arrayPtr = new bool[size];
for (int i = 0; i < size; i++)
{
if (intsetObject.arrayPtr[i])
arrayPtr[i] = intsetObject.arrayPtr[i];
}
}
IntSet::~IntSet()
{
--numOfArray;
delete [] arrayPtr;
arrayPtr = NULL;
}
int IntSet::determineHighest(int tempArray[])
{
int temp = tempArray[0];
for (int i = 1; i < MAXINITIALSIZE; i++)
{
if (tempArray[i] > temp)
temp = tempArray[i];
else
continue;
}
return temp;
}
IntSet& IntSet::operator=(const IntSet &intsetObject) //ask about IntSet&
{
cout << "inside operator=" << endl;
if (&intsetObject != this)
{
for (int i = 0; i < size; i++)
{
cout << &arrayPtr[i] << endl;
}
delete [] arrayPtr; //HEAP ERROR HERE!
for (int i = 0; i < size; i++)
{
cout << &arrayPtr[i] << endl;
}
size = intsetObject.size
arrayPtr = new bool[size]();
for (int i = 0; i < size; i++)
{
if (intsetObject.arrayPtr[i])
arrayPtr[i] = intsetObject.arrayPtr[i];
}
}
return *this;
}
ostream& operator<<(ostream &output, const IntSet &intsetObject)
{
output << "{ ";
for (int i = 0; i < intsetObject.size; i++)
{
if (intsetObject.arrayPtr[i] == true)
{
output << i << " ";
}
else
continue;
}
output << "}";
return output;
}
//main
#include "intset.h"
int main() {
IntSet object2(9);
IntSet object4(3,6);
object4 = object2;
return 0;
}
This can only happen if arrayPtr is accessed with a negative index. I suspect your defaults for a,b,c,d,e are -1 in the declaration for IntSet::IntSet, so it is writing to arrayPtr[-1] in the set-true loop. Check for tempArray[i] >= 0 there.
Also, you can't print the array after you have deleted it, so you should remove those lines after the delete, although they should be "harmless" in that only garbage will be printed, but who knows - the OS could release the page containing the array and it could segfault your program.
Finally, you should not test if (intsetObject.arrayPtr[i]) in the copy & = operators. Otherwise all "false" elements in the source array become uninitialized in the destination array (new bool[size] does not initialize the array to all false).