c++ the dynamic array of class allocation fails (memory leak) - c++

edit1: add a running tiny version.
I wrote a cpp file including some classes. When I test it in a single file, everything works but when I link it with other c files, the data I stored in the array in the class changed. I know there must be something wrong with my memory allocation so I changed it into dynamic one using new
but cant figure out where or how to fix
work in single .cpp file
in a file called test.app
class Board
{
public:
int **grid;
bool done;
int result;
public:
Board()
{
grid = new int*[3];
for(int i = 0; i < 3; ++i){
grid[i] = new int[3];
}
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
grid[i][j]=0;
}
}
done=false;
result=0;
}
}
class Node
{
public:
Board **arr;
//double heuristic;
bool done;
int result;
int prevx, prevy;
int next_turn;
public:
Node()
{
arr = new Board*[3];
for(int i=0;i<3;i++)
{
arr[i] = new Board[3];
}
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
arr[i][j] = new Board();
}
}
done = false;
//heuristic=0;
result = 0;
prevx = -1;
prevy = -1;
next_turn=1;
}
}
and the code where thing go wrong:
Treenode *head; //treat as global variable
void agent_start( int this_player )
{
//nothing to do
//cout << "here all good" << endl;
head = new Treenode();
//cout << head << endl;
m = 0;
return;
}
int agent_second_move( int board_num, int prev_move )
{
for(int i=0;i<9;i++)
{
for(int j=0;j<9;j++)
{
if(head->arr[res_boardx][res_boardy].grid[cordx][cordy] == 1)
{
cout << "here cant print" << endl;
head->move2(i,j,-1);
cout << "here cant print" << endl;
}
else if(head->arr[res_boardx][res_boardy].grid[cordx][cordy] == -1)
{
cout << "here cant print" << endl;
head->move2(i,j,1);
}
}
}
in test.h
extern int port;
extern char *host;
#ifdef __cplusplus
extern "C" {
#endif
extern char *host;
#ifdef __cplusplus
}
#endif
#ifdef __cplusplus
extern "C" {
#endif
// parse command-line arguments
void agent_parse_args( int argc, char *argv[] );
// called at the beginning of a series of games
void agent_init();
// called at the beginning of each game
void agent_start( int this_player );
int agent_second_move(int board_num, int prev_move );
int agent_third_move(int board_num,int first_move,int prev_move);
int agent_next_move( int prev_move );
void agent_last_move( int prev_move );
// called at the end of each game
void agent_gameover( int result, int cause );
// called at the end of the series of games
void agent_cleanup();
#ifdef __cplusplus
}
#endif
in main.cpp
int main(int argc, char *argv[]){
agent_start(1);
int b = agent_second_move(1,1);
}
the output is:
[1] 26904 illegal hardware instruction
or
segmentation fault
before when I delared
class Node
{
public:
Board arr[3][3]; ///
in Node class.
the working version before which caused data in treenode changed
class Board
{
public:
int grid[3][3];
bool done;
int result;
public:
Board()
{
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
grid[i][j]=0;
}
}
done=false;
result=0;
}
}
class Node
{
public:
Board arr[3][3];
//double heuristic;
bool done;
int grid[3][3];
int result;
int prevx, prevy;
int next_turn;
public:
Node()
{
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
arr[i][j] = Board();
grid[i][j]=0;
}
}
done = false;
//heuristic=0;
result = 0;
prevx = -1;
prevy = -1;
next_turn=1;
}
}
Treenode *head;
head = new Treenode();
void print_map(){
for(int i=0;i<9;i++)
{
for(int j=0;j<9;j++)
{
int res_boardx, res_boardy, cordx, cordy;
res_boardx = (i-1)/3;
res_boardy = (i-1)%3;
cordx = (j-1)/3;
cordy = (j-1)%3;
cout << head->arr[res_boardx][res_boardy].grid[cordx][cordy];
}
cout << endl;
}
}
the 2D array printed out is below when I call print function outside this
file which is wrong since it should either be 1 or 0 or -1.
433000000
107312758200000000
000000000
000000000
000000000
000000000
00000-1000
000000000
000000000

You are not following the rule of 5. You have some memory allocation in constructor, so you need a non default destructor, to correctly free everything, as long as explicit move/copy constructors and assignment operators.
If possible, you should stick to standard containers like std::vector which handle all the corner cases for you.

Related

for-loop help getting wrong output

I am writing a code using classes and am getting the wrong output, this is my function definitions:
void PrintCard(int c)
{
int Rank = c%13;
int Suit = c/13;
const char NameSuit[5] = "SCDH";
const char NameRank[14] = "23456789XJQKA";
cout << NameRank[Rank] << NameSuit[Suit];
}
CardSet::CardSet()
{
Card = NULL;
nCards = 0;
}
CardSet::CardSet(int c)
{
Card = new int[c];
for(int i = 0; i > c; i++)
{
Card[i] = (i % 52);
}
}
CardSet::~CardSet()
{
delete[] Card;
}
bool CardSet::IsEmpty() const
{
return nCards == 0;
}
void CardSet::Print() const
{
for(int i=0; i > nCards; i++)
{
PrintCard(i);
}
}
int CardSet::Size() const
{
return nCards;
}
This is my main
cout << "Testing constructors, Print(), Size() & IsEmpty():" << endl;
CardSet CardSet1; // empty cCardSet
CardSet CardSet2(12); // CardSet with 12 cards
if(CardSet1.IsEmpty()) cout<<"CardSet1 is empty"<<endl;
else cout<<"CardSet1 has "<< CardSet1.Size() <<" cards" << endl;
if(CardSet2.IsEmpty()) cout<<"CardSet2 is empty"<<endl;
else cout<<"CardSet2 has "<< CardSet2.Size() <<" cards" << endl;
cout << "Printout of CardSet1: ";
CardSet1.Print();
cout << "Printout of CardSet2: ";
CardSet2.Print();
cout << endl;
when i am compiling i am getting the correct value (0) for cardset1 however for cardset2 instead of outputting a value of 12, which is what should be the output i am getting very high numbers that are changing each time i compile. i think something is wrong with my for loops or memory allocation.
this is also what the class definition looks like:
class CardSet
{
public:
CardSet();
CardSet(int);
~CardSet();
int Size() const;
bool IsEmpty() const;
void Shuffle();
int Deal();
void Deal(int,CardSet&,CardSet&);
void Deal(int,CardSet&,CardSet&,CardSet&,CardSet&);
void AddCard(int);
void MergeShuffle(CardSet&);
void Print() const;
private:
int* Card;
int nCards;
};
any help would be greatly appreciated !!
Cheers
In CardSet::CardSet change this
for(int i = 0; i > c; i++)
to this
for (int i = 0; i < c; i++)
Also in CardSet::Print change this
for(int i=0; i > nCards; i++)
To this:
for (int i = 0; i < nCards; i++)
Finally, add nCards = c; to CardSet::CardSet.
void CardSet::Print() const
{
for(int i=0; i > nCards; i++)
{
PrintCard(i);
}
}
must be
void CardSet::Print() const
{
for(int i=0; i < nCards; i++)
{
PrintCard(i);
}
}
to correct the end test, and you have the same problem in CardSet::CardSet(int c) which must be
CardSet::CardSet(int c)
{
nCards = c;
Card = new int[c];
for(int i = 0; i < c; i++)
{
Card[i] = (i % 52);
}
}
where nCards must also be set.
In a for the test indicates if the loop continues, not if it ends
for (inits; test; changes) ...
is equivalent to
init;
while (test) {
...
changes;
}
Out of that there is no separator in PrintCard doing cout << NameRank[Rank] << NameSuit[Suit]; so may be you also need to add something like a space in Print :
void CardSet::Print() const
{
for(int i=0; i < nCards; i++)
{
PrintCard(i);
cout << ' ';
}
}
or in PrintCard to also separate the two fields like
cout << NameRank[Rank] << ' ' << NameSuit[Suit] << endl;
Note you can simplify
const char NameSuit[5] = "SCDH";
const char NameRank[14] = "23456789XJQKA";
cout << NameRank[Rank] << NameSuit[Suit];
to be
cout << "23456789XJQKA"[Rank] << "SCDH"[Suit];
Or if you really want to have the arrays I encourage you to not give a size, that avoid problems if you change the literal string and forget to also change the size, so
const char NameSuit[] = "SCDH";
const char NameRank[] = "23456789XJQKA";
For instance having :
#include <iostream>
using namespace std;
class CardSet
{
public:
CardSet();
CardSet(int);
~CardSet();
int Size() const;
bool IsEmpty() const;
void Shuffle();
int Deal();
void Deal(int,CardSet&,CardSet&);
void Deal(int,CardSet&,CardSet&,CardSet&,CardSet&);
void AddCard(int);
void MergeShuffle(CardSet&);
void Print() const;
private:
int* Card;
int nCards;
};
void PrintCard(int c)
{
int Rank = c%13;
int Suit = c/13;
cout << "23456789XJQKA"[Rank] << ' ' << "SCDH"[Suit] << endl;
}
CardSet::CardSet()
{
Card = NULL;
nCards = 0;
}
CardSet::CardSet(int c)
{
nCards = c;
Card = new int[c];
for(int i = 0; i < c; i++)
{
Card[i] = (i % 52);
}
}
CardSet::~CardSet()
{
delete[] Card;
}
bool CardSet::IsEmpty() const
{
return nCards == 0;
}
void CardSet::Print() const
{
for(int i=0; i < nCards; i++)
{
PrintCard(i);
}
}
int CardSet::Size() const
{
return nCards;
}
int main(void)
{
CardSet cs(5);
cs.Print();
}
Compilation and execution :
pi#raspberrypi:/tmp $ g++ -pedantic -Wall -Wextra c.cc
pi#raspberrypi:/tmp $ ./a.out
2 S
3 S
4 S
5 S
6 S
pi#raspberrypi:/tmp $
You should review it (the loop)
void CardSet::Print() const
{
for(int i=0; i > nCards; i++)//## reconsider it
{
PrintCard(i);
}
}

xcode not giving an output while using pthread library

smaller programs work just fine, but as soon as I start writing over 30 lines, it seems like xcode wants to execute, but nothing really happens. This is the code I have written, I can't find any errors, but maybe there is an explanation for my issues.
`
using namespace std;
int errorCounter = 0;
class Vector
{
public:
Vector(unsigned int size = 10000) : size_(size)
{
vector_ = new int[size_];
set(0);
}
~Vector()
{
delete[] vector_;
}
bool setAndTest(int n)
{
set(n);
return test(n);
}
private:
void set(int n)
{
for(unsigned int i=0; i<size_; i++) vector_[i] = n;
}
bool test(int n)
{
for(unsigned int i=0; i<size_; i++) if(vector_[i] != n) return false;
return true;
}
int* vector_;
unsigned int size_;
};
Vector vec;
int threads = 50;
void *writer(void *ptr)
{
int *threadIDconvert = (int*)(ptr);
while(1)
{
if (!vec.setAndTest(*threadIDconvert)) {
errorCounter++;
cout<<"error arrised from thread ID " << *threadIDconvert << " error number" << errorCounter<<endl;
usleep(100000);
}
}
return NULL;
}
int main() {
//int threads;
//cout << "enter an amount of threads: min 1 max 100" <<endl;
//cin>>threads;
if(threads<1){cout<<"you screwed up"<<endl; return 0;}
else if (threads>100) {cout<<"you screwed up"<<endl; return 0;}
pthread_t threadID[threads];
for (int x=0; x<=threads; x++) {
pthread_create(&threadID[x], NULL, writer, &vec);
}
for (int CID=0; CID<=threads; CID++) {
pthread_join(threadID[CID], NULL);
}
return 0;
}
`
Hope someone can help out, and sorry that I didn't show all of my includes, I don't know how to on stack overflow (and I know I can use mutex and what not, this is just a try out program :-) )

Calling two Queue class function in a loop

I have problem with this code of mine. Whenever i call two function of the class, and in those class, there is if-else statement, and print the output on screen, it will only run the if clause of the two functions and not the else. How can i fix this?
For example:
This is my Queue.h file:
#ifndef QUEUE_H
#define QUEUE_H
class Queue {
private:
//private variables
int arr_size;
char *arr;
int head;
int tail;
int count;
public:
Queue(int); //constructor
//functions
int enqueue(char);
int dequeue(char&);
};
#endif
This is my Queue.cpp file:
#include <iostream>
#include "Queue.h"
using namespace std;
Queue::Queue(int size) {
//initializing
arr_size = size;
arr = new char[size];
for (int i = 0; i < arr_size; i++) {
arr[i] = NULL;
}
head = 0;
tail = 0;
count = 0;
}
int Queue::enqueue(char value) {
if (count<arr_size) //if array is not full, execute below
{
arr[tail++] = value; //pass value of first-to-last element in array
count++; //counting the input value
cout << "\nEnqueue Value: "<< arr[tail-1];
return 0;
}
else {
tail = 0;
cout << "\nArray is full. Value cannot be write: " << value;
return -1;
}
}
int Queue::dequeue(char &read_val) {
if (count !=0) { //if array has elements, execute below
read_val = arr[head]; //pass-by-reference the value of first-to-last element in array to parameter of function
cout <<"\nDequeue Value: "<<read_val;
arr[head] = NULL;
count--;
if (head++ == arr_size) {
head = 0;
}
return 0;
}
else if (count ==0) {
cout << "\nArray is empty. Cannot be dequeue";
return -1;
}
}
And this is what my Source file:
#include "Queue.h"
#include <iostream>
using namespace std;
int main() {
int n;
cout << "Please enter the desired size of the array: ";
cin >> n;
char read_val = NULL;
Queue myqueue(n);
char arr[] = "Hello World, this is ELEC3150";
int size = sizeof(arr)-1;
int count = 0;
for (int i = 0; i < 5; i++) {
myqueue.enqueue(arr[count]);
count++;
myqueue.dequeue(read_val);
}
If i enter the size of the array to be less than 5, it must print the error message saying the array is full in the enqueue function and the array is empty in the dequeue function but did not.

I have an array of objects. These objects have arrays of integers and I can't access them within the array

This is my class
class Process {
public:
Process();
void createBurstArray(int *bursts, int sizeOfArray);
void createIOArray(int *IO, int capacity);
int *burstArray;
int *ioArray;
int currentBurst;
int currentIO;
int currentState;
};
Process::Process()
{
}
void Process::createBurstArray(int *bursts, int capacity){
burstArray = new int[capacity];
burstArray = bursts;
};
void Process::createIOArray(int *IO, int capacity) {
ioArray = new int[capacity];
ioArray = IO;
for (int i = 0; i < capacity; i++)
};
void main(){
int processOneBursts[7] = { 12,10,15,11,9,10,11 };
int processOneIO[6] = { 44,52,21,42,31,77 };
Process processes[9];
Process one;
processes[0] = one;
one.createBurstArray(processOneBursts, 7);
one.createIOArray(processOneIO, 6);
}
When I try accessing the ioArray
one.ioArray[1]
I get the value stored in the ioArray at index 1, butw hen I try accessing the ioArra through my object array index it doesn't work:
for (int i = 0; i < 9; i++) {
cout << processes[i].ioArray[i] << endl;
}
What am I doing wrong?
#include <iostream>
using namespace std;
class Process {
public:
// Process();
void createBurstArray(int *bursts, int sizeOfArray);
void createIOArray(int *IO, int capacity);
int *burstArray;
int *ioArray;
int currentBurst;
int currentIO;
int currentState;
};
int main()
{
Process p[10];
for (int i = 0; i < 9; i++) {
p[i].ioArray = new int[1];
}
for (int i = 0; i < 9; i++) {
p[i].ioArray[0] = i;
}
for (int i = 0; i < 9; i++) {
cout << p[i].ioArray[0] << endl;
}
return 0;
}
This works, i think you didn't initialize the dynamic array.
You are object of the class with default constructor which means all the elements in the class will be uninitialized including the element int *ioArray;.
And you are trying to access ioArray in the for loop which is road set to segmentation fault.
To correct this, you must initialize the element before using them.
Also, Your below function is problematic.
void Process::createIOArray(int *IO, int capacity) {
ioArray = new int[capacity];
ioArray = IO;
}
This is a memory leak, since you have assign ioArray to IO ,new int[capacity] memory will not be freed.
Solution:
#include <iostream>
using namespace std;
class Process {
public:
Process();
void createBurstArray(int sizeOfArray);
void createIOArray(int capacity);
int *burstArray;
int *ioArray;
int currentBurst;
int currentIO;
int currentState;
// Don't forget to delete burstArray, ioArray in destructor.
};
void Process::createIOArray(int capacity) {
ioArray = new int[capacity];
};
void Process::createBurstArray(int sizeOfArray) {
burstArray = new int[sizeOfArray];
};
Process::Process(){
createIOArray(10);
createBurstArray(10);
// Similarly you have to initialize other members of the class
}
int main()
{
Process processes[9];
for (int i = 0; i < 9; i++) {
cout << processes[i].ioArray[i] << endl;
}
}

C++ change from struct to classes [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 11 years ago.
I am looking to change this from struct to classes and use a header file to hold the class.
What would you suggest in way of changing it over. The code all works. There is no problem there. just a simple change over question.
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
struct printype
{
char dots[8][15];
int unknown15; // can have values of 0..127
string serial11_14; // 8 characters 00000000...99999999
int year8; // without century, 0..99
int month7; // 1..12
int day6; // 1..31
int hour5; // 0..23
int minute2; // 0..59
};
int getunknown15(); // prototypes
string getserial11_14();
int getyear8();
int getmonth7();
int getday6();
int gethour5();
int getminute2();
int setunknown15(int); //------------------------- protos
string setserial11_14(string);
int setyear8(int);
int setmonth7(int);
int setday6(int);
int sethour5(int);
int setminute2(int);
// int array and display info for array
void setup(char[8][15]);
// display array
void darray(char[8][15]);
// displays printer information
void dpinfo(printype);
// set parrity
void spar(char[8][15]);
// fill array
void ftarray(printype &); //----------------------end protos
//-------------------------------------
void main ()
{
printype pt;
pt.unknown15=getunknown15();
pt.unknown15=setunknown15(pt.unknown15);
pt.serial11_14=getserial11_14();
pt.serial11_14=setserial11_14(pt.serial11_14);
pt.year8=getyear8();
pt.year8=setyear8(pt.year8);
pt.month7=getmonth7();
pt.month7=setmonth7(pt.month7);
pt.day6=getday6();
pt.day6=setday6(pt.day6);
pt.hour5=gethour5();
pt.hour5=sethour5(pt.hour5);
pt.minute2=getminute2();
pt.minute2=setminute2(pt.minute2);
cout <<"-----------------------------------------------------"<<endl;
cout <<" Lets Get Started"<<endl;
cout <<"-----------------------------------------------------"<<endl;
setup(pt.dots); // sets up the array
dpinfo(pt); // prints out the final array
ftarray(pt);
spar(pt.dots);
darray(pt.dots);
}
int getunknown15()
{
printype tem;
cout <<"-----------------------------------------------------"<<endl;
cout <<" Enter the Unkown Variable (0-127): ";
cin >>tem.unknown15;
cout <<"-----------------------------------------------------"<<endl;
return tem.unknown15;
}
string getserial11_14()//------------------------------------------ starts the get information sets
{
printype tem;
cout <<" Enter the Serial Variable (8char long): ";
cin >>tem.serial11_14;
cout <<"-----------------------------------------------------"<<endl;
return tem.serial11_14;
}
int getyear8()
{
printype tem;
cout <<" Enter the Year Variable (2char long): ";
cin >>tem.year8;
cout <<"-----------------------------------------------------"<<endl;
return tem.year8;
}
int getmonth7()
{
printype tem;
cout <<" Enter the Month Variable (2char long): ";
cin >>tem.month7;
cout <<"-----------------------------------------------------"<<endl;
return tem.month7;
}
int getday6()
{
printype tem;
cout <<" Enter the Day Variable (2char long): ";
cin >>tem.day6;
cout <<"-----------------------------------------------------"<<endl;
return tem.day6;
}
int gethour5()
{
printype tem;
cout <<" Enter the Hour Variable (2char long): ";
cin >>tem.hour5;
cout <<"-----------------------------------------------------"<<endl;
return tem.hour5;
}
int getminute2()
{
printype tem;
cout <<" Enter the Minute Variable (2char long): ";
cin >>tem.minute2;
cout <<"-----------------------------------------------------"<<endl;
return tem.minute2;
}
//-----------------------------------------------------------put functions (adds info to the array)
int setunknown15(int tem)
{
printype pp;
if (tem>127||tem<0)
{
cout << "Error" << endl;
return 0;
}
else
{
pp.unknown15 = tem;
return pp.unknown15;
}
}
string setserial11_14(string tem)
{
printype pp;
if(tem.size() !=8)
{
cout <<"nope.jpg"<<endl;
return 0;
}
else
{
for (int i = 0; i < 8; i++)
{
if(!isdigit(tem.at(i)))
{
cout<<"nope.jpg"<<endl;
return 0;
}
}
pp.serial11_14=tem;
return pp.serial11_14;
}
}
int setyear8(int tem)
{
printype pp;
if(tem>99||tem<0)
{
cout<<"nope.jpg"<<endl;
return 0;
}
else
{
pp.year8=tem;
return pp.year8;
}
}
int setmonth7(int tem)
{
printype pp;
if(tem>12||tem<1)
{
cout<<"nope.jpg"<<endl;
return 0;
}
else
{
pp.month7=tem;
return pp.month7;
}
}
int setday6(int tem)
{
printype pp;
if(tem>31||tem<1)
{
cout<<"nope.jpg"<<endl;
return 0;
}
else
{
pp.day6=tem;
return pp.day6;
}
}int sethour5(int tem)
{
printype pp;
if(tem>23||tem<0)
{
cout<<"nope.jpg"<<endl;
return 0;
}
else
{
pp.hour5=tem;
return pp.hour5;
}
}
int setminute2(int tem)
{
printype pp;
if(tem>59||tem<0)
{
cout<<"nope.jpg"<<endl;
return 0;
}
else
{
pp.minute2=tem;
return pp.minute2;
}
}
void setup(char tem[8][15])
{
for (int x=0;x<8;x++)// set to all blanks
{
for (int y=0;y<15;y++)
{
tem[x][y]=' ';
}
}
}
void darray(char tem[8][15])
{
for (int x=0;x<8;x++)// set to all blanks
{
cout <<"\t-------------------------------"<<endl;
cout <<"\t|";
for (int y=0;y<15;y++)
{
cout << tem[x][y];
cout<<"|";
}
cout <<"\n";
}
cout <<"\t-------------------------------"<<endl;
}
void dpinfo(printype mc)
{
cout <<"The unknown is:\t"<<mc.unknown15<<"\nThe String is:\t"<<mc.serial11_14<<"\n Time:\n\n Year: 20"<<mc.year8<<" month: "<<mc.month7<<"\n day: "<<mc.day6<<" hour: "<<mc.hour5<<"\n minute: "<<mc.minute2<<endl;
}
void spar(char tem[8][15])
{
int count=0;
for (int x=0;x<7;x++)
{
for (int y=0;y<15;y++)
{
if(tem[x][y]=='*')
{
count+=1;
}
}
if(count%2==0)
{
tem[x][0]='*';
}
}
count=0;
for (int a=0;a<7;a++)
{
for (int z=0;z<7;z++)
{
}
}
}
void ftarray(printype &pt)
{
int tem=0;
for (int x=1;x<15;x++)
{
switch(x)
{
case 1:
{
tem=pt.minute2;
break;
}
case 4:
{
tem=pt.hour5;
break;
}
case 5:
{
tem=pt.day6;
break;
}
case 6:
{
tem=pt.month7;
break;
}
case 7:
{
tem=pt.year8;
break;
}
case 9:
{
for (int j = 1; j < 8; j++)
{
pt.dots[j][x] = '*';
}
}
case 10:
{
tem=atoi(pt.serial11_14.substr(6,2).c_str());
break;
}
case 11:
{
tem=atoi(pt.serial11_14.substr(4,2).c_str());
break;
}
case 12:
{
tem=atoi(pt.serial11_14.substr(2,2).c_str());
break;
}
case 13:
{
tem=atoi(pt.serial11_14.substr(0,2).c_str());
break;
}
case 14:
{
tem=pt.unknown15;
break;
}
}
if(x==1||x==4||x==5||x==6||x==7||x==10||x==11||x==12||x==13||x==14)
{
if (tem>=64)
{
pt.dots[1][x]='*';
tem-=64;
}
if (tem>=32)
{
pt.dots[2][x]='*';
tem-=32;
}
if (tem>=16)
{
pt.dots[3][x]='*';
tem-=16;
}
if (tem>=8)
{
pt.dots[4][x]='*';
tem-=8;
}
if (tem>=4)
{
pt.dots[5][x]='*';
tem-=4;
}
if (tem>=2)
{
pt.dots[6][x]='*';
tem-=2;
}
if (tem>=1)
{
pt.dots[7][x]='*';
tem-=1;
}
}
}
}
In C++, struct and class is the same thing, other than the default access level. All you need to do is replace
struct printype
{
//...
};
with
class printype
{
public:
//...
};
You can also probably replace the functions that take a printype as argument by value with member functions:
void dpinfo(printype);
becomes
class printype
{
public:
//....
void dpinfo();
};
and will operate on this rather than the parameter.
Methods that return an object printype can become constructors.
I suspect however you have several issues with your code:
int getunknown15()
{
printype tem;
cout <<"-----------------------------------------------------"<<endl;
cout <<" Enter the Unkown Variable (0-127): ";
cin >>tem.unknown15;
cout <<"-----------------------------------------------------"<<endl;
return tem.unknown15;
}
Here, for example, you don't need the tem variable... it does nothing. You can directly read an int an return that, tem will be destroyed on function exit anyway.
Maybe you're looking for a member function, for example:
int printype::setyear8(int tem)
{
if(tem>99||tem<0)
{
cout<<"nope.jpg"<<endl;
return 0;
}
else
{
this->year8=tem;
return this->year8;
}
}
This way the object is modified and you don't lose changes. However, your coding style suggests little to no knowledge of oop. I suggest reading a good book before continuing, as I doubt that, as it is, the answer will make much sense to you.
First of all, a struct and a class are the same in C++, only difference is that a struct is default public and a class is default private. All you do is change struct to class
Looking at your code, however, I'm assuming you are converting from C to C++ and want to add your functions as methods to the class. To do this, you simply add the prototypes to the class declaration and then add the class space to the function implementations. You should also add any relevant constructors and a destructor in necessary
In a h file
class Printype {
char **dots;
int unknown15; // can have values of 0..127
string serial11_14; // 8 characters 00000000...99999999
int year8; // without century, 0..99
int month7; // 1..12
int day6; // 1..31
int hour5; // 0..23
int minute2; // 0..59
//Constructors
Printype(); //Default
Printype(const Printype &cpy); //Copy
Printype(int yr, int mo, int d, int hr, int min); //Sample initializer
//Destrutor
~Printype();
//Methods (only gonna do 2 for example)
int getYear();
void setYear(int y);
};
In a cpp or cc file
#include "printype.h"
Printype::Printype() {
dots = new char*[8];
for(int i=0;i<8;++i) {
dots[i] = new char[15];
}
unknown15 = 0; serial11_14 = ""; year8 = 0;
month7 = 0; day6 = 0; hour5 = 0;minute2 = 0;
}
Printype::Printype(const Printype &cpy) {
//Deep copy all values from cpy to this
}
Printype::Printype() {
dots = new char*[8];
for(int i=0;i<8;++i) {
dots[i] = new char[15];
}
unknown15 = 0; serial11_14 = ""; year8 = yr;
month7 = mo; day6 = d; hour5 = hr;minute2 = min;
}
//Destructor (free allocated memory)
Printype::~Printype() {
for(int i=0;i<8;++i) {
delete[] dots[i]; dots[i] = NULL;
}
delete[] dots; dots = NULL;
}
//Methods
int Printype::getYear() {
return year8;
}
void Printype::setYear(int y) {
year8 = y;
}
You should also implement an = operator. Hope this gets you started and answers your question though. You should really read up on some general OOP in addition to C++ syntax, patterns, etc. A lot of this will likely look foreign and not make much sense, and it will take to long to explain in this forum. There are tons of resources online regarding this material so you should try to read up on it.