Pointers with cout in C++ - c++

I am in the process of learning C++ and SDL, and when I tried to print the content of an array I ran into some confusion. I have an array with two values in it, 2 and 3. When I want to print the values like this:
int* test = myApp.countDivisions(5);
std::cout << "Horizontal: " << *test<< std::endl;
std::cout << "Vertical: " << *(test+1) << std::endl;
I get:
Horizontal: -858993460
Vertical: -858993460
But when I write:
int* test = countDivisions(5);
int foo = *(test);
int boo = *(test+1);
std::cout << "Horizontal: " << foo << std::endl;
std::cout << "Vertical: " << boo << std::endl;
I get:
Horizontal: 2
Vertical: 3
I am confused as to why this happens. If anyone could explain why this behaviour happens, it would be great! I am aware that I should not be using C arrays in C++, but I am still interested in understanding what is happenning here!.
Edit: I modified a typo in the first example.
Also I got asked what my countDivisions(int) function does so here is the entire code:
#include <iostream>
#include <SDL.h>
class SDLApplication {
private:
//This is the window of the application:
SDL_Window* AppWindow;
//This is the surface displayed by the window:
SDL_Surface* WindowSurface;
SDL_Renderer* Renderer;
//This is the name of the App:
std::string AppName;
//These are the dimensions of the window displaying the App
int WindowWidth;
int WindowHeight;
public:
SDLApplication(std::string name) {
AppWindow = NULL;
WindowSurface = NULL;
AppName = name;
WindowHeight = 0;
WindowWidth = 0;
Renderer = NULL;
}
int* countDivisions(int divisions) {
//This helper functions takes as input the number of divisions on the screen and returns an array that tells
//us how many horizontal and vertical divisions we have, assuming we divide linearly starting from the right corner.
int horizontal = 0;
int vertical = 0;
int i = 0;
int divTemp = pow(2,i);
int divCount = divTemp;
int temp;
while (divCount < divisions) {
if (i % 2 == 0) {
//Our power of two is pair, so we are adding horizontal divisions
horizontal += divTemp;
}
else {
//Our power of two is odd, so we are adding vertical divisions
vertical += divTemp;
}
++i;
divTemp = pow(2,i);
temp = divCount + divTemp;
if ( temp> divisions) {
if (i % 2 == 0) {
//Our power of two is pair, so we are adding horizontal divisions
horizontal += divisions-divCount;
}
else {
//Our power of two is odd, so we are adding vertical divisions
vertical += divisions-divCount;
}
}
divCount =temp;
}
int result[] = { horizontal, vertical };
return result;
}
}
int main(int argc, char* argv[])
{
SDLApplication myApp("SDL_Test");
int* test = myApp.countDivisions(5);
std::cout << "Horizontal: " << *test << std::endl;
std::cout << "Vertical: " << *(test + 1) << std::endl;
return 0;
}

I think printing *int is undefined behaviour - it is kind of meaningless. This expression is a type. Its a bit like saying "where is human" rather then "where is the human called bob" (ok, bit of a rubbish analogy), a type does not have an address on its own.
Your second example int* test is a variable named test which has a type of int* (pointer to an integer). You set the value of the pointer test to something (whatever myApp.countDivisions(5); returns - you should tell us what that returns).
Then:
int foo = *(test);
int boo = *(test+1);
foo is an integer variable that you set to the value of what test points to - and not the address itself. boo is set to the contents of the next address (address of test + 1).
If you want to print the address of the pointers you should do:
std::cout << "Horizontal: " << test << std::endl;
If you want to print the value of what the pointer is pointing to you should do:
std::cout << "Horizontal: " << *test << std::endl;
This is called dereferencing. See this little example: https://godbolt.org/z/CzHbq6
update: updated as per question update
You are returning a pointer to a local variable called result. That variable is destroyed at the end of your countDevisions() function, which will lead to undefined behaviour (which you are seeing) meaning anything can happen!. See here for an example of that with the warnings printed out: https://godbolt.org/z/gW2XS4
"A" fix for that is to change the scope of result by making its lifetime the entire life of the program, this can be done by making it static. Note I do this for demonstration only - this is not a good solution, but see it here working: https://godbolt.org/z/goQJzx
Perhaps a better solution would be to return a container from the standard template library (STL) like std::vector (something like an array): https://godbolt.org/z/3DOyhq
Or perhaps (after reading your code properly) you don't really even want an array, it seems you just want two values: vertical and horizontal. So you could define your own struct and use that - this seems more optimal: https://godbolt.org/z/RmUM39. This also makes more sense to the user of your function by being able to reference horizontal/vertical by name and not by some array index.

TLDR: "turn on warnings" and search for "c++ return multiple values"
You need to include iostream and define three classes, and fix two additional typos.
#include <iostream>
typedef int SDL_Window;
typedef int SDL_Surface;
typedef int SDL_Renderer;
This results in code that gives a useful warning message, which tells you that SDLApplication::countDivisions returns the address of a local variable or temporary. As you later attempt to use that temporary object which has gone out of scope, the result is, not surprisingly, undefined behavior.
Your function returns multiple values. You could have created an std::tuple object, but I would just define a struct so you can return one value, with named members.
struct Divisions {
int horizontal;
int vertical;
};
class SDLApplication {
...
Divisions countDivisions(int divisions) {
...
return Divisions{ horizontal, vertical };
}
};
see also
Return multiple values to a method caller
Returning multiple values from a C++ function

Related

Outputting a string pointer array

I'm having a bit of trouble figuring out exactly what I am doing wrong here, and haven't found any posts with the same issue. I am using a dynamic array of strings to hold a binary tree with the root at [0], first row of children, left to right, at [1] and [2], etc. While I haven't debugged that output format yet, I am much more concerned as to why that specific line is crashing my program.
I thought it was a pointer de-referencing issue, but outStream << &contestList[i] prints addresses as I'd expect, and outStream << *contestList[i] throws errors as I'd expect them to.
//3 lines are from other functions/files
typedef string elementType;
typedef elementType* elementTypePtr;
elementTypePtr contestList = new elementType[arraySize];
void BinTreeTourneyArray::printDownward(ostream &outStream)
{
int row = 1;
for (int i = 0; i < getArraySize(); i++)
{
outStream << contestList[i]; //this is crashing the program
if (isPowerOfTwo(i))
{
outStream << endl;
row++;
}
else
{
outStream << ":";
}
}
}
arraySize is a private member arraySize = ((2 * contestants) - 1) where contestants is the number of contestants in my tournament. Each round or "row" in the tree is synonymous with a tournament bracket. If there are n contestants, then there are 2n-1 nodes needed in the tree. The issue wouldn't be with this function.
getArraySize() { return arraySize; }
Turns out elementTypePtr contestList = new elementType[arraySize]; was the issue. contestList was a private member of the class, then I threw this line in a function declaring a local variable of the same name that disappears after the function ends. No biggie, except for the fact that I needed it in the print function...Oops.

How to use values created inside a loop function?

I would like to know which one would be the best way of using values created inside a loop, outside of that loop. I have for example the function:
void Loop(int a)
{
// recursion loop execution
for ( int i = 0; i < 10; i++ )
{
int new_a = a + i;
}
}
I would like to use that "new_a" as it is being "looped" in another function which is plotting a graph and only needs the "yAxe" value. Like that:
int main ()
{
int a = 5;
plot (x,Loop(int a);
}
I know I could create an array with the values of the loop but I wouldn't like to store them and for big plottings would be too much memory.
Any local variable will be destroyed when the scope of them be finished. For example, in your code new_a will be destroyed when the for loop is finished, and the a is destroyed when the function be finished. I mean if you care about memory, don't be worry.
If I understand you correctly, you want to call Loop multiple times (like e.g. Loop(a)) and each call you should get the next "iteration" of the loop?
That would have been easy if C++ had continuations which it doesn't. Instead it can be emulated by using classes and objects and operator overloading.
For example:
class LoopClass
{
public:
LoopClass(int initial_value = 0)
: current_value{initial_value}
{
}
int operator()(int a)
{
return a + current_value++;
}
private:
int current_value;
};
It can be used as such:
LoopClass Loop; // The value initialized with zero
int a = 5;
std::cout << "First call : " << Loop(a) << '\n';
std::cout << "Second call: " << Loop(a) << '\n';
The above code, if put into a program, should print
First call : 5
Second call: 6

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 );

c++ pointer to function and void pointers iteraction resulting in wierd things

Im making a little project at home about genetic algorithm. But im trying to make it generic, so i use pointers to function and void pointers. but i think it might be making some problems.
The main goal of this section of the project is to get a pointer to a function, which return a certain struct. The struct containing a void pointer
and when im trying to view the value of where it points too it isn`t quite right.I suspect that maybe the interaction between these two might be causing me some problems.
details:
struct:
struct dna_s{
int size;
void *dna;
};
population is a class contaning all the population for the process. besides, it contains 2 functions as well, init_func and fitter_func which are both pointers to functions.
pointer to function definition:
typedef dna_s (*init_func_t)();
typedef int (*fitter_func_t)(dna_s);
population class:
class population{
private:
// Parameters
int population_size;
node *pop_nodes;
// Functions
init_func_t init_func;
fitter_func_t fitter_func;
public:
population(int pop_size,init_func_t initialization_func){
// Insert parameters into vars.
this->population_size = pop_size;
this->init_func = initialization_func;
// Create new node array.
this->pop_nodes = new node[this->population_size];
for(int i = 0;i < this->population_size; i++){
dna_s curr_dna = this->init_func();
char *s = static_cast<char*>(curr_dna.dna);
cout << s << endl;
this->pop_nodes[i].update_dna(curr_dna);
}
}
};
You can see that in the constructor im inserting a pointer to function, init_func. this function is generating random words.
init_func:
dna_s init_func(){
string alphanum = "0123456789!##$%^&*ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
char init_s[STRING_SIZE+1] = {};
dna_s dna;
// Generate String
for(int i = 0; i < STRING_SIZE; i++){
init_s[i] = alphanum[rand() % alphanum.size()];
}
cout << "-->" << init_s << endl;
// Insert into struct.
dna.size = STRING_SIZE;
dna.dna = static_cast<void*>(&init_s);
// Return it
return dna;
}
the main function is not so interesting but it might be connected:
int main(){
// Init srand
srand(time(0));
// Parameters
int population_size = 10;
population pop(population_size, init_func);
}
now for the interesting part, whats the problem?
in the init_func the cout prints:
-->e%wfF
which is all good
but in the population class the cout prints:
e%Ω²(
and the wierd thing is the first 2 characters will always be the same, but the other 3 will always be this string Ω²(.
example:
-->XaYN7
XaΩ²(
-->oBK9Q
oBΩ²(
-->lf!KF
lfΩ²(
-->RZqMm
RZΩ²(
-->oNhMC
oNΩ²(
-->EGB6m
EGΩ²(
-->osafQ
osΩ²(
-->3#NQt
3#Ω²(
-->D62l0
D6Ω²(
-->tV#mu
tVΩ²(
Your code has a few lifetime issues. In your dna_S struct:
void *dna;
This is a pointer, it points to an object that exists elsewhere. Then, in your init_func:
dna_s init_func(){
...
char init_s[STRING_SIZE+1] = {};
dna_s dna;
...
dna.dna = static_cast<void*>(&init_s);
...
return dna;
}
init_s is a variable that exists inside init_func, you make dna point to that variable and then leave the function. init_s ceases to exist at this point, dna is pointing nowhere useful when the population constructor gets it, causing undefined behavior.
You could work around that by allocating memory with new char[], like you did for pop_nodes, but you are responsible for deleting that memory when it is no longer used.

using .size() member function on a vector passed by reference

I'm having some confusion with the usage of the .size() member function of vector.
So what I have is an object that displays a series of bitmaps in sequence, these bitmaps are stored as pointers in a vector. This vector is then passed by reference "&" in the construction of my "animation" object, which does all the work cycling through the bitmaps.
Everything works as I expected except that calling .size() on my referenced vector of bitmap pointers, which does not return anything, though I know the vector has contents.
This then causes the animation to cycle through normally, then it trips up because its trying to access an element that is out of bounds, due to .size() returning nothing, messing up my bounds checking.
My only guess is that my syntax is not correct, or that i'm not properly understanding the usage.
#include "animation.h"
#include "helperFunctions.h"
#include <vector>
#include <iostream>
animation::animation(int x, int y, SDL_Renderer* screenRenderer, std::vector<SDL_Texture*>& sprites) {
_x = x;
_y = y;
_sprites = &sprites;
_frames = sprites.size() - 1;///this is to be used as an indexer, eg. 0 frames is 1 in reality, 3 is 4...
_currentFrame = 0;///first frame index
mainScreen = screenRenderer;
_finished = false;
}
animation::animation(const animation& orig) {
}
animation::~animation() {
std::cout << "animation object deleted!" << std::endl;
}
void animation::cycleFrame() {
applyTexture(_x, _y, (*_sprites)[_currentFrame], mainScreen);
std::cout << "_currentFrame: " << _currentFrame << std::endl;
std::cout << "_frames : " << _frames << std::endl;
_currentFrame++;
if (_currentFrame == _frames) {
_finished = true;
}
}
Also I should add that i'm not asking for help with anything SDL, just the whole vector.size() thing.
Thank in advance, any help would be greatly appreciated.
UPDATE:
So I did some digging and it seems like .size() is also returning as 0 on the vector before it is even being passed to the constructor...
in main() I have:
std::vector<SDL_Texture*> explosion16;
explosion16.reserve(16);
for (int i = 0; i < 16; i++) {
explosion16[i] = loadTexture(loadImage("gfx/explosions/explosion_16/e" + to_string(i) + ".bmp"));
}
cout << "explosion16.size() : " << explosion16.size() << endl;/////this returns as zero, 0
Based on your comment:
If you use reserve(), that does not increment the size, only the capacity.
You should either use resize(), and than you can use the indexer to initialize the members, or keep reserve and use push_back() instead of [].
in below line :
_frames = sprites.size() - 1;
_frames might be -1 in case sprites.size() is zero.
if(sprites.size() > 0)
_frames = sprites.size() - 1;