Ok i'm pretty new to c++ (I think what we are learning is somehow an hybrid of c and c++).
I've found alot of anwsers to my question, sadly all of them where in C using malloc.
struct A {
int randomStuff = 0;
};
struct B {
int numOfA= 5; // In reality this number is variable.
A** arrayOfA;
};
The struct are given to us. Now I need to allocate and fill this array with pointers to, I guess, A pointers. <- Correct me here if I'm wrong pointers are still quite complex for me.
A * a1 = new A;
A * a2 = new A;
B * b = new B;
// Allocate space for the array...
b->arrayOfA = new A*[numOfA];
// Next I want to initialize the pointers to NULL
for(int i; i < b->numOfA; i++){
b->arrayOfA[i] = NULL;
}
// In another function I would the assign a value to it
b->arrayOfA[0] = a1;
b->arrayOfA[1] = a2;
The way I see it is that b->arrayOfA needs to point to an array of A struct...somehow like this
b->arrayOfA = new A*;
A * arr[numOfA];
b->arrayOfA = arr;
My brain is bleeding.
How do I correctly allocate it and assign existing values(A structs) to it?
*edit
It would appear that the code was working as intended and that my display was causing me issues. Basically, I needed an array "arrayOfA[]" in which I would put the pointers to an A struct. Effectively making the result of this:
cout << arrayOfA[0]->randomStuff // 0 would be displayed
To be 0.
You could allocate an array of pointers and for each of them allocate an array of your objects
int x = 5, y = 6;
b->arrayOfA = new A*[x]; //array of pointers
for(int i=0;i<x;i++){
b->arrayOfA[i] = new A[y]; //matrix (array of arrays)
}
for(int i=0;i<x;i++){
delete[] b->arrayOfA[i]; //don't forget to free memory
}
delete[] b->arrayOfA;
You should be able to just use a vector:
#include <vector>
int main()
{
vector<A> vector_of_a;
vector_of_a.push_back(a1); //store a1 in the vector
vector_of_a.push_back(a2); //store a2 in the vector
//...
std::cout << "Number of A's: " << vector_of_a.size() << std::endl;
std::cout << vector_of_a[0].randomStuff << std::endl; //prints 0 as specified but with '.' not '->' Objects are still on the heap, and not the stack.
}
The A's in the vector are stored on the heap, but you don't need to manage the memory yourself (no need for malloc/free or new/delete.
The A objects will be disposed of correctly when the vector goes out of scope.
You also get
You can push in pointers to objects too, but this reduces the usefulness of the vector as you then have to do your own memory management for the objects:
#include <vector>
int main()
{
A* a1 = new A();
A* a2 = new A();
vector<A> vector_of_a;
vector_of_a.push_back(a1); //store pointer to a1 in the vector
vector_of_a.push_back(a2); //store pointer to a2 in the vector
//...
std::cout << "Number of A's: " << vector_of_a.size() << std::endl;
std::cout << vector_of_a[0]->randomStuff << std::endl; //prints 0 as specified
//...
for (auto i : vector_of_a)
{
delete (i);
}
vector_of_a.clear();
}
If you really don't want to use a vector, then I reccommend turning your struct B into a fully fledged class.
It gives you the benefit of encapsulation, functions to manage the data are stored within the class, and the class does the memory management and doesn't leave it to the
user's code to manage and clear up behind it:
class B
{
public:
array_of_A(unsigned int size);
~array_of_A();
bool init_array();
unsigned int get_size();
A** get_array();
private:
unsigned int num_of_A;
A** array_of_A;
}
B::array_of_A(unsigned int size)
{
num_of_a = size;
array_of_A = new A*[size]; //create array
memset (array_of_A, nullptr, size); //initialise contents to nullptr
}
B::~B()
{
for(unsigned int i = 0; i < num_of_a; i++)
{
delete array_of_a[i]; //delete each A
}
delete[](array_of_a); //delete the array of pointers.
}
unsigned int B::get_size()
{ return num_of_A; }
A** B::get_array()
{ return array_of_A; }
int main()
{
B b((5)); //most vexing parse...
b.get_array()[0] = new A();
b.get_array()[1] = new A();
b.get_array()[2] = new A();
std::cout << b.get_array()[0]->randomStuff << std::endl //prints 0 as requested
} //b goes out of scope, destructor called, all memory cleaned up
aaaand by internalising the memory management and supporting arbitarilly long arrays, we've just started implementing a (much) simpler version of vector. But good for practice/learning.
Related
I'm playing around with destructors and I don't understand why I get an error for this code when the main function terminates.
#include <iostream>
#include <math.h>
#include <string>
#include <cstdint>
#include <cassert>
using namespace std;
class RGBA {
uint8_t _red, _blue, _green, _alpha;
int *_arr;
int _length;
public:
RGBA(int *arr, int length, uint8_t r = 0, uint8_t b = 0, uint8_t g = 0, uint8_t a = 255):
_red (r), _blue (b), _green (g), _alpha (a) {
_arr = arr;
_length = length;
}
~RGBA() {
cout << "Destroying object" << endl;
delete[] _arr;
}
void print() {
for (int i = 0; i < _length; ++i) {
cout << _arr[i] << endl;
}
cout << static_cast<int>(_red) << " " << static_cast<int>(_blue) << " " << static_cast<int>(_green) << " " << static_cast<int>(_alpha) << endl;
}
};
int main() {
int arr[3] = {1,2,3};
RGBA rgba(arr, 3);
rgba.print();
cin.get();
return 0;
}
It outputs, but then when I press Enter, it prints 'Destroying object' with the following error "This may be due to a corruption of the heap, which indicates a bug in testcpp.exe or any of the DLLs it has loaded.".
1
2
3
0 0 0 255
I use VS2010 on Win7.
The automatic storage duration variable int arr[3] will be automatically deallocated when the enclosing function exits.
Trying to delete[] it causes undefined behavior. Only objects allocated with new[] can be deallocated with delete[].
In your case, this is effectively what is happening:
int arr[3] = {1,2,3};
delete[] arr;
Your arr in main is in automatic storage. You pass it into your object, which assumes ownership and assumes the memory was dynamically allocated with new.
You should only delete [] what you new [].
~RGBA() {
cout << "Destroying object" << endl;
delete[] _arr;
}
Here was your problem because delete didn't work on static array, It always work for dynamic array. delete only work for new
int *arr = new int[3];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
this will work perfectly.
The array you are passing, arr is being allocated on the stack in your main function. You then pass the pointer to your RGBA instance which then deletes the array in its destructor. As it was not dynamically allocated in the first place, this is a bad thing.
Deleting the array in the destructor indicates that you mean to transfer ownership of the array to that class. To do that, you need to either pass a dynamically allocated array or allocate a new array in the constructor and copy the contents of the one passed by parameter.
If you do not need ownership, simply remove the delete call in the destructor.
That's because you aren't supposed to delete the array.
The implementation of your destructor is correct, but the array is not allocated with new[], so you must not de-allocating with delete[].
If you'd replace your array in your main with it's modernized cousin, std::array, and the pointer in your class by std::vector, you would see that assigning a array to a vector would require an allocation on the heap and a copy of each element in your array.
A quick way to fix the code would be to allocate the array using new[]:
int* arr = new int[3]{1, 2, 3};
RGBA rgba(arr, 3);
rgba.print();
Now that the array is allocated using new[], it can be safely deleted using delete[].
However, please note that in most modern code, you either use std::array<T, N>, std::vector<T> or std::unique_ptr<T[]> to manage arrays.
The resulting code that use arrays and vectors would be like this:
#include <iostream>
#include <vector>
#include <array>
struct RGBA {
std::uint8_t red = 0, green = 0, blue = 0, alpha = 255;
std::vector<int> arr;
RGBA(std::vector<int> _arr) : arr{std::move(_arr)} {}
// No destructor needed. vector manages it's own resources.
void print() {
for (auto&& number : arr) {
std::cout << number << std::endl;
}
std::cout << static_cast<int>(red) << " "
<< static_cast<int>(blue) << " "
<< static_cast<int>(green) << " "
<< static_cast<int>(alpha) << std::endl;
}
};
int main() {
// Create a constant array on the stack the modern way
constexpr std::array<int, 3> arr{1, 2, 3};
// Copy array elements in the vector
RGBA rgba{std::vector<int>{arr.begin(), arr.end()}};
rgba.print();
cin.get();
}
I know how to dynamically allocate space for an array in C. It can be done as follows:
L = (int*)malloc(mid*sizeof(int));
and the memory can be released by:
free(L);
How do I achieve the equivalent in C++?
Specifically, how do I use the new and delete[] keywords? Especially in the context of creating/destroying a linked list node, or creating and destroying an array whose size is given by a variable during compile time?
int* L = new int[mid];
delete[] L;
for arrays (which is what you want) or
int* L = new int;
delete L;
for single elements.
But it's more simple to use vector, or use smartpointers, then you don't have to worry about memory management.
std::vector<int> L(mid);
L.data() gives you access to the int[] array buffer and you can L.resize() the vector later.
auto L = std::make_unique<int[]>(mid);
L.get() gives you a pointer to the int[] array.
Following Info will be useful :
Source : https://www.learncpp.com/cpp-tutorial/6-9a-dynamically-allocating-arrays/
Initializing dynamically allocated arrays
If you want to initialize a dynamically allocated array to 0, the syntax is quite simple:
int *array = new int[length]();
Prior to C++11, there was no easy way to initialize a dynamic array to a non-zero value (initializer lists only worked for fixed arrays). This means you had to loop through the array and assign element values explicitly.
int *array = new int[5];
array[0] = 9;
array[1] = 7;
array[2] = 5;
array[3] = 3;
array[4] = 1;
Super annoying!
However, starting with C++11, it’s now possible to initialize dynamic arrays using initializer lists!
int fixedArray[5] = { 9, 7, 5, 3, 1 }; // initialize a fixed array in C++03
int *array = new int[5] { 9, 7, 5, 3, 1 }; // initialize a dynamic array in C++11
Note that this syntax has no operator= between the array length and the initializer list.
For consistency, in C++11, fixed arrays can also be initialized using uniform initialization:
int fixedArray[5] { 9, 7, 5, 3, 1 }; // initialize a fixed array in C++11
char fixedArray[14] { "Hello, world!" }; // initialize a fixed array in C++11
One caveat, in C++11 you can not initialize a dynamically allocated char array from a C-style string:
char *array = new char[14] { "Hello, world!" }; // doesn't work in C++11
If you have a need to do this, dynamically allocate a std::string instead (or allocate your char array and then strcpy the string in).
Also note that dynamic arrays must be declared with an explicit length:
int fixedArray[] {1, 2, 3}; // okay: implicit array size for fixed arrays
int *dynamicArray1 = new int[] {1, 2, 3}; // not okay: implicit size for dynamic arrays
int *dynamicArray2 = new int[3] {1, 2, 3}; // okay: explicit size for dynamic arrays
you allocate memory using the new operator and release a pointer using delete operator. Note that you can't delete normal variables, only pointers and arrays can be deleted after accomplishing their task.
int * foo;
foo = new int [5];
delete[] foo;
a complete program
#include <iostream>
#include <new>
using namespace std;
int main ()
{
int i,n;
int * p;
cout << "How many numbers would you like to type? ";
cin >> i;
p= new (nothrow) int[i];
if (p == nullptr)
cout << "Error: memory could not be allocated";
else
{
for (n=0; n<i; n++)
{
cout << "Enter number: ";
cin >> p[n];
}
cout << "You have entered: ";
for (n=0; n<i; n++)
cout << p[n] << ", ";
delete[] p;
}
return 0;
}
result
How many numbers would you like to type? 5
Enter number : 75
Enter number : 436
Enter number : 1067
Enter number : 8
Enter number : 32
You have entered: 75, 436, 1067, 8, 32,
In C++ we have the methods to allocate and de-allocate dynamic memory.The variables can be allocated dynamically by using new operator as,
type_name *variable_name = new type_name;
The arrays are nothing but just the collection of contiguous memory locations, Hence, we can dynamically allocate arrays in C++ as,
type_name *array_name = new type_name[SIZE];
and you can just use delete for freeing up the dynamically allocated space, as follows,
for variables,
delete variable_name;
for arrays,
delete[] array_name;
You need to be extremely careful when using raw pointers with dynamic memory but here is a simple example.
int main() {
// Normal Pointer To Type
int* pX = nullptr;
pX = new int;
*pX = 3;
std::cout << *pX << std::endl;
// Clean Up Memory
delete pX;
pX = nullptr;
// Pointer To Array
int* pXA = nullptr;
pXA = new int[10]; // 40 Bytes on 32bit - Not Initialized All Values Have Garbage
pXA = new int[10](0); // 40 Bytes on 32bit - All Values Initialized To 0.
// Clean Up Memory To An Array Of Pointers.
delete [] pXA;
pXA = nullptr;
return 0;
} // main
To avoid memory leaks; dangling pointers, deleting memory to early etc. Try using smart pointers. They come in two varieties: shared and unique.
SomeClass.h
#ifndef SOME_CLASS_H
#define SOME_CLASS_H
class SomeClass {
private:
int m_x;
public:
SomeClass();
explicit SomeClass( x = 0 );
void setX( int x );
int getX() const;
private:
SomeClass( const SomeClass& c ); // Not Implemented - Copy Constructor
SomeClass& operator=( const SomeClass& c ); Not Implemented - Overloaded Operator=
}; // SomeClass
#endif // SOME_CLASS_H
SomeClass.cpp
#include "SomeClass.h"
// SomeClass() - Default Constructor
SomeClass::SomeClass() :
m_x( x ) {
} // SomeClass
// SomeClass() - Constructor With Default Parameter
SomeClass::SomeClass( int x ) :
m_x( x ) {
} // SomeClass
// setX()
void SomeClass::setX( int x ) {
m_x = x;
} // setX
// getX()
void SomeClass::getX() const {
return m_x;
} // getX
Old Way Of Using Dynamic Memory
#include <iostream>
#include "SomeClass.h"
int main() {
// Single Dynamic Pointer
SomeClass* pSomeClass = nullptr;
pSomeClass = new SomeClass( 5 );
std::cout << pSomeClass->getX() << std::endl;
delete pSomeClass;
pSomeClass = nullptr;
// Dynamic Array
SomeClass* pSomeClasses = nullptr;
pSomeClasses = new SomeClasses[5](); // Default Constructor Called
for ( int i = 0; i < 5; i++ ) {
pSomeClasses[i]->setX( i * 10 );
std::cout << pSomeSomeClasses[i]->getX() << std::endl;
}
delete[] pSomeClasses;
pSomeClasses = nullptr;
return 0;
} // main
The problem here is knowing when, where and why to delete memory; knowing who is responsible. If you delete the memory to manage it and the user of your code or library assumes you didn't and they delete it there is a problem since the same memory is trying to be deleted twice. If you leave it up to the user to delete it and they assumed you did and they don't you have a problem and there is a memory leak. This is where the use of smart pointers come in handy.
Smart Pointer Version
#include <iostream>
#include <memory>
#include <vector>
#include "SomeClass.h"
int main() {
// SHARED POINTERS
// Shared Pointers Are Used When Different Resources Need To Use The Same Memory Block
// There Are Different Methods To Create And Initialize Shared Pointers
auto sp1 = std::make_shared<SomeClass>( 10 );
std::shared_ptr<SomeClass> sp2( new SomeClass( 15 ) );
std::shared_ptr<SomeClass> sp3;
sp3 = std::make_shared<SomeClass>( 20 );
std::cout << "SP1: " << sp1->getX() << std::endl;
std::cout << "SP2: " << sp2->getX() << std::endl;
std::cout << "SP3: " << sp3->getX() << std::endl;
// Now If you Reach The Return Of Main; These Smart Pointers Will Decrement
// Their Reference Count & When It Reaches 0; Its Destructor Should Be
// Called Freeing All Memory. This Is Safe, But Not Guaranteed. You Can
// Release & Reset The Memory Your Self.
sp1.reset();
sp1 = nullptr;
sp2.reset();
sp2 = nullptr;
sp3.reset();
sp3 = nullptr;
// Need An Array Of Objects In Dynamic Memory?
std::vector<std::shared_ptr<SomeClass>> vSomeClasses;
vSomeClasses.push_back( std::make_shared<SomeClass>( 2 ) );
vSomeClasses.push_back( std::make_shared<SomeClass>( 4 ) );
vSomeClasses.push_back( std::make_shared<SomeClass>( 6 ) );
std::vector<std::shared_ptr<SomeClass>> vSomeClasses2;
vSomeClasses2.push_back( std::shared_ptr<SomeClass>( new SomeClass( 3 ) ) );
vSomeClasses2.push_back( std::shared_ptr<SomeClass>( new SomeClass( 5 ) ) );
vSomeClasses2.push_back( std::shared_ptr<SomeClass>( new SomeClass( 7 ) ) );
// UNIQUE POINTERS
// Unique Pointers Are Used When Only One Resource Has Sole Ownership.
// The Syntax Is The Same For Unique Pointers As For Shared Just Replace
// std::shared_ptr<SomeClass> with std::unique_ptr<SomeClass> &
// replace std::make_shared<SomeClass> with std::make_unique<SomeClass>
// As For Release Memory It Is Basically The Same
// The One Difference With Unique Is That It Has A Release Method Where Shared Does Not.
auto mp1 = std::make_unique<SomeClass>( 3 );
mp1.release();
mp1.reset();
mp1 = nullptr;
// Now You Can Also Do This:
// Create A Unique Pointer To An Array Of 5 Integers
auto p = make_unique<int[]>( 5 );
// Initialize The Array
for ( int i = 0; i < 5; i++ ) {
p[i] = i;
}
return 0;
} // main
Here Are Reference Links To Both Shared & Unique Pointers
https://msdn.microsoft.com/en-us/library/hh279669.aspx
https://msdn.microsoft.com/en-us/library/hh279676.aspx
I am having problems with my constructor in class World.
I created a 2D array with pointers where each entry in the array is of type Organism, hence the line of code:
Organism* grid[20][20];
When I run my program, I only see
hello
and after that, I get a message saying that my program has stopped working. I'm pretty sure it's the line of code
grid[i][j]->symbol = ' ';
that's causing the problem. Just to see what would happen, I changed that line to
grid[i][j];
and didn't get any errors. But, the moment I put ->, I seem to get errors.
Is there a reason why my program stops working after I put ->? Any help would be appreciated.
This is my code:
#include <iostream>
using namespace std;
class Organism
{
public:
char symbol;
};
class World
{
public:
World();
private:
Organism* grid[20][20];
};
int main()
{
World world;
return 0;
}
World::World()
{
for(int i = 0; i < 20; i++)
for(int j = 0; j < 20; j++)
{
cout << "hello" << endl;
grid[i][j]->symbol = ' ';
cout << "here" << endl;
}
}
You have an array of pointers to Organism.
Pointers can not hold any data other than an address. They can only point to memory (that holds data).
Your array's pointers does not point to anything, thats why you get undefined behaviour when you try to assign data to where the pointers point at.
You need to allocate memory for your array.
Organism grid[20][20]; // Create an array of objects (not pointers).
/* ... */
grid[i][j].symbol = ' ';
Same using dynamic memory:
class World {
public:
World();
~World(); // Rule of Three.
World(const World&) = delete; // Rule of Three.
World& operator=(const World&) = delete; // Rule of Three.
private:
Organism** grid;
};
World::World() {
grid = new Organism*[20]; // Allocate memory to point to.
for(std::size_t i = 0; i != 20; ++i) {
grid[i] = new Organism[20]; // Allocate memory to point to.
for(std::size_t j = 0; j != 20; ++j) {
cout << "hello" << endl;
grid[i][j].symbol = ' ';
cout << "here" << endl;
}
}
}
// Destructor needed to deallocate memory (otherwise it will leak).
World::~World()
{
for (std::size_t i = 0; i != 20; ++i) {
delete[] grid[i];
}
delete[] grid;
}
Now you can see how complicated it gets when using dynamic memory and why it's recommended to prefer to use automatic storage duration (i.e. create objects, not pointers and new/delete).
Even better is to use a container from the standard library for storing your elements as e.g. std::vector.
Related:
What is The Rule of Three?
Change
Organism* grid[20][20];
To
Organism grid[20][20];
and use
grid[i][j].symbol = '';
instead of
grid[i][j]->symbol = '';
and add a default constructor to Organism
class Organism
{
Organism();
...
}
or make Organism a struct
struct Oranism
{
...
}
This is the default constructor with no parameters. By default, this allocates space for a
double array of size 10 and assigns a default value of 0 to each of them.
its a ""class"" , I m not sure what i m doing right or wrong..
I fill the public body functions , but my output is nothing suppose to print 0000000000
, I m very new to coding.
class DataVector
{
private:
DataType *m_data;//Pointer to dynamically allocated memory that holds all items
UIntType m_size;//Size of the m_data array
public:
DataVector()
{
double *m_data = new double[m_size];
for (int i = 0; i < m_size; i++)
{
*m_data = 0;
m_data++;
}
}
void PrintItems()
{
for (int i = 0; i < m_size; i++)
{
cout << *m_data << " ";
m_data++;
}
}
};
void TestDataVector()
{
{
DataVector d1;
d1.PrintItems();
}
}
There are a few problems with this implementation of yours:
You are not initializing m_size
You change the value of the pointer m_data which is supposed to hold the address of first member of the array. So, at the end of the initializer, m_data is pointing to a spot one after the block you had allocated by new.
same in the printItems member function, but here the pointer already points to an invalid location.
Also, because you are allocating memory in the constructor, you should also define a destructor to free that memory.
In my Main Window I create an instance of PointerClass, which holds an array of pointers to PointerObject (I want to be able to access it with PointerObject[X][Y] and delete it the same way, and check if PointerObject[X][Y] == NULL (which is WHY I use pointers)) and I don't want a solution with vectors.
#define X 10
#define Y 10
class PointerObject
{
public:
int X;
int Y;
}
class PointerClass
{
public:
PointerObject *ArrayOfPointerObjects[X][Y];
}
PointerMethod(&PointerClass);
Then, in my PointerMethod I create the Pointer to an array:
PointerMethod(PointerClass *pointerClass)
{
// don't know the right way to do this
pointerClass->ArrayOfPointerObjects= new PointerObject[X][Y];
// set all pointers in the array to NULL - is this needed?
for (int x=0; x < X; x++)
{
for (int y=0; y < Y; y++)
{
pointerClass->ArrayOfPointerObjects[x][y] = NULL;
}
}
// trying to store some data here
pointerClass->ArrayOfPointerObjects[0][0] = new PointerObject;
// trying to delete it
delete pointerClass->ArrayOfPointerObjects[0][0];
// or trying this:
delete[] pointerClass->ArrayOfPointerObjects[0][0];
// causes access violation or doesn't work
}
I earlier asked this without success or questions about the wrong type.
Delete pointer to multidimensional array in class through another pointer - how?
I can access the array, check if it's NULL. but when I call delete / delete[] pointerClass->ArrayOfPointerObjects[x][y] it seem to delete the pointer to pointerClass instead of the element at [X][Y] and I want to delete the pointer at location [X][Y] and not the pointerClass and I don't want to delete the whole array.
How can I do this without complicating it too much? I guess my array isn't truely an array of pointers, just a pointer to an array. But I want it to be an array of pointers stored in a pointer or something. Still the importance is how I access it and how I delete the elements in the array. I need to be able to check if the pointer is NULL and if not be able to Delete that single PointerObject.
The importance of this is that I want to:
Access the array of PointerObjects with [X][Y]
Check if an object in the array is NULL (=needs pointers)
Delete a single item in the array of pointers without destroying the pointer to the PointerClass object or deleting the rest of the array. Just delete a single PointerObject at a certain X, Y location in the array so that [X][Y] after deletion = NULL.
If there's too much confusion or likeness with my other thread it is because people told me thing I had no wish for and it led off subject, here it is better illustrated how it works and how I want it to work like.
hmm, i think something like this
#include <iostream>
class Foo
{
int i_;
int j_;
public:
Foo(int i, int j) : i_(i), j_(j) {}
void print_coords()
{
std::cout << this << " (" << i_ << ',' << j_ << ')' << std::endl;
}
};
class Bar
{
public:
Foo *arr[5][5];
};
class Que
{
public:
void init(Bar *b)
{
for(int i=0; i<5; i++)
for(int j=0; j<5; j++)
b->arr[i][j] = new Foo(i, j);
}
void print(Bar *b, int i, int j)
{
try {
if(b->arr[i][j])
b->arr[i][j]->print_coords();
else
throw 0;
} catch (int e) {
std::cout << &b->arr[i][j] << " points to null" << std::endl;
}
}
void rem(Bar *b, int i, int j)
{
delete b->arr[i][j];
b->arr[i][j] = 0;
}
};
int main()
{
Bar *b = new Bar();
Que *q = new Que();
q->init(b);
q->print(b, 2, 2);
q->rem(b, 2, 2);
q->print(b, 2, 2);
return 0;
}