Understand pointers - c++

#include <iostream>
using namespace std;
class idk{
public:
int x;
int y;
};
void obj(idk* obj[]){
obj[0]-> x = 1000;
obj[0]-> y = 30;
}
int main(){
idk *z[5];
obj(z);
cout << z[0]->x;
return 0;
}
I am just trying out how to use pointers. The problem is when I set my array 'z' size to 5 or any number it doesn't do anything, however when I make it 10 it then prints out the correct output. Ive tried pasting the code into an online compiler and it also plays up there but with other numbers. Is my code wrong or missing some things?

In this
idk *z[5];
you declare 5 idk pointers. These are only pointers that you can assign to point at idks, but you have not created any actual idks. When you later dereference the first pointer you get undefined behavior since it's not actually pointing at an idk:
void obj(idk* obj[]){
obj[0]-> x = 1000; // BOOM
Making the array of pointers actually point at idk instances can be made in many different ways. Here's one:
#include <iostream>
class idk{
public:
int x;
int y;
};
void obj(idk* obj[]){
obj[0]-> x = 1000;
obj[0]-> y = 30;
}
int main(){
idk instances[5];
idk *z[5]{
&instances[0],
&instances[1],
&instances[2],
&instances[3],
&instances[4],
}; // now all five point at one idk instance each
obj(z);
std::cout << z[0]->x;
}
Another option would be to skip the pointer array completely:
#include <iostream>
class idk {
public:
int x;
int y;
};
void obj(idk obj[]) {
obj[0].x = 1000;
obj[0].y = 30;
}
int main() {
idk z[5];
obj(z);
std::cout << z[0].x;
}

Related

Perform same operation on different class members without duplicate code

How do I perform the same operation on different class members without duplicating code?
I have a function which creates an object of type Farm, and then performs some kind of a calculation on its members (in this case, it prints the member variable, but the code I am currently working on is too complex to copy here in its entirety):
#include <iostream>
#include <String>
class Farm
{
public:
int cows = 1;
int chickens = 2;
int mules = 3;
};
using namespace std;
void count_animals()
{
Farm* animal_farm = new Farm;
cout << animal_farm->chickens;
}
int main()
{
string animals_to_count = "count my chickens";
if (animals_to_count == "count my chickens")
count_animals();
if (animals_to_count == "count my cows")
count_animals();
if (animals_to_count == "count my mules")
count_animals();
return 0;
}
"Count my chickens" is hard-coded in main(). However, in the problem I am working on right now, animals_to_count will come from another function as an argument.
Is it possible to print cows/chickens/mules of animal_farm without using n if statements in count_animals, where n is the number of member variables?
To further clarify my problem: what I am trying to do is have 1 if statement in count_animals() which will identify which member of Farm is printed (change ->chickens to ->cows or to ->mules).
Is what I am trying possible? If not, are there other ways to work around this?
Putting your variables into a vector or other container may be the right answer.
Alternately, you can make a worker function (that you may wish to be private or protected), and getter functions with almost no code. This lets you write your complicated statistics-extraction once, with slim "getters" that make it visible in your preferred way.
class Farm
{
public:
int cows = 1;
int chickens = 2;
int mules = 3;
int get_cow_stats() {return get_complicated_thing(self.cows);}
int get_chicken_stats() {return get_complicated_thing(self.chickens);}
int get_mule_stats() {return get_complicated_thing(self.mules);}
private:
int get_complicated_thing(int animals);
};
Perhaps a pointer-to-member is what you are looking for?
#include <iostream>
using namespace std;
class Farm
{
public:
int cows = 1;
int chickens = 2;
int mules = 3;
};
int Farm::* getMemberPtr(int whichMember)
{
switch (whichMember)
{
case 0: return &Farm::chickens;
case 1: return &Farm::cows;
case 2: return &Farm::mules;
}
throw invalid_argument("");
}
void count_animals(int Farm::*member)
{
Farm animal_farm;
cout << animal_farm.*member;
}
int main()
{
int animals_to_count = ...; // 0, 1, 2, etc
int Farm::* member = getMemberPtr(animals_to_count);
count_animals(member);
return 0;
}
Online Demo
Use std::vector and constant indices:
class Farm
{
public:
std::vector<int> animal_quantity(3);
const int cow_index = 0;
const int chickens_index = 1;
const int mules_index = 2;
};
When referring to the quantity of cows:
std::cout << animal_quantity[cow_index] << "\n";

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.

Size of an object without using sizeof in C++

This was an interview question:
Say there is a class having only an int member. You do not know how many bytes the int will occupy. And you cannot view the class implementation (say it's an API). But you can create an object of it. How would you find the size needed for int without using sizeof.
He wouldn't accept using bitset, either.
Can you please suggest the most efficient way to find this out?
The following program demonstrates a valid technique to compute the size of an object.
#include <iostream>
struct Foo
{
int f;
};
int main()
{
// Create an object of the class.
Foo foo;
// Create a pointer to it.
Foo* p1 = &foo;
// Create another pointer, offset by 1 object from p1
// It is legal to compute (p1+1) but it is not legal
// to dereference (p1+1)
Foo* p2 = p1+1;
// Cast both pointers to char*.
char* cp1 = reinterpret_cast<char*>(p1);
char* cp2 = reinterpret_cast<char*>(p2);
// Compute the size of the object.
size_t size = (cp2-cp1);
std::cout << "Size of Foo: " << size << std::endl;
}
Using pointer algebra:
#include <iostream>
class A
{
int a;
};
int main() {
A a1;
A * n1 = &a1;
A * n2 = n1+1;
std::cout << int((char *)n2 - (char *)n1) << std::endl;
return 0;
}
Yet another alternative without using pointers. You can use it if in the next interview they also forbid pointers. Your comment "The interviewer was leading me to think on lines of overflow and underflow" might also be pointing at this method or similar.
#include <iostream>
int main() {
unsigned int x = 0, numOfBits = 0;
for(x--; x; x /= 2) numOfBits++;
std::cout << "number of bits in an int is: " << numOfBits;
return 0;
}
It gets the maximum value of an unsigned int (decrementing zero in unsigned mode) then subsequently divides by 2 until it reaches zero. To get the number of bytes, divide by CHAR_BIT.
Pointer arithmetic can be used without actually creating any objects:
class c {
int member;
};
c *ptr = 0;
++ptr;
int size = reinterpret_cast<int>(ptr);
Alternatively:
int size = reinterpret_cast<int>( static_cast<c*>(0) + 1 );

Array counting 858993460 in each slot

I'm trying to create a two dimensional array, which I can use as coordinates for a map to be displayed. For the moment I'm just trying to get a character to display on screen over and over to create an effect in a box with the dimensions of the array. But at each coordinate it just displays some long number (maybe like the slots are empty or something?)
I feel like it might be a loss of data from the class member to the main function, but I'm really just guessing.
For example, I'm looking for an output something like this:
11111
11111
11111
11111
Source code:
#include <iostream>
using namespace std;
class Map_Blocks
{
public:
int Map_Width = 60;
int Map_Height = 15;
int Map_Array [15][60];
int Generate();
int Display();
};
int Map_Blocks::Generate()
{
int x, y;
for(y=0;y<Map_Height;y++)
{
for(x=0;y<Map_Width;x++)
{
Map_Array[y][x]=1;
}
}
return 0;
}
int Map_Blocks::Display()
{
int x, y;
for(y=0;y<Map_Height;y++)
{
for(x=0;y<Map_Width;x++)
{
cout<<Map_Array[y][x];
}
cout<<endl;
}
return 0;
}
int main(void)
{
Map_Blocks Size;
cout<<"Map Width ="<<Size.Map_Width<<endl;
cout<<"Map Height ="<<Size.Map_Height<<endl;
Map_Blocks disp;
disp.Display();
return 0;
}
You never call Generate() to initialize the array's content.
Add:
disp.Generate();
before the call to Display().

Getting Segmentation Error in code

Trying to create a function which will fill a vector of objects with initialized objects.
Please help.
ERROR: Segmentation fault (core dumped)
EDIT:
Ok so, problem seems to be occurring in the line when trying to access OBJ[0].age.
Also forgot the Point2d function comes from OpenCV libraries which I forgor to add, but they dont seem to contribute to the error in any way.
#include <iostream>
#include <vector>
struct objtracker
{
int age;
vector<int> frID;
vector<Point2d> cent;
objtracker()
{
age = 1;
}
~objtracker()
{
// Destroy ObjectTracker
}
};
vector<objtracker> OBJ;
void create_new_tracker(vector<objtracker> OBJ,Point2d cent,int frameID,objtracker O){
O.cent.push_back(cent);
O.frID.push_back(frameID);
}
int main(){
Mat Y;
Y = imread("hor.jpeg",CV_LOAD_IMAGE_COLOR);
Point2d J;
J.x = 100;
J.y = 100;
int frameID = 100;
objtracker O;
create_new_tracker(OBJ,J,frameID,O);
create_new_tracker(OBJ,J,frameID,O);
create_new_tracker(OBJ,J,frameID,O);
create_new_tracker(OBJ,J,frameID,O);
create_new_tracker(OBJ,J,frameID,O);
cout<<OBJ[0].age<<"\n";
return 1; }
void create_new_tracker(vector<objtracker> OBJ,Point2d cent,int frameID,objtracker O){
O.cent.push_back(cent);
O.frID.push_back(frameID);
}
You never add any objtracker's to OBJ inside this function.
And even if you did, it won't be reflected as it is passed by value
You might want something like
void create_new_tracker(vector<objtracker> &OBJ,Point2d cent,int frameID,objtracker O)
{
O.cent.push_back(cent);
O.frID.push_back(frameID);
OBJ.push_back(O);
}