NEVERMIND, FIXED IT. for loop issue
I'm trying to do some number crunching with formatted output, and I've run into a problem with half my output not printing. I've written a small test code to illustrate the problem:
#include <iostream>
int testF(){
for (int i; i<10; i++) {
std::cout << i << "\n";
}
return 0;
}
int main(){
std::cout << "START_(this_line_seems_to_be_causing_problems)\n";
int sret = 1;
sret = testF();
std::cout << sret << "\n";
std::cout << "END\n";
return 0;
}
The problem seems to hinge on the line std::cout << "START_(this_line_seems...".
If I comment out this line, it will print the contents of testF(). If I don't then testF() does not print, although it does give a return value.
It's important that I can print from both main and my functions. Is there a way I can do both?
try initializing i:
int testF(){
for (int i = 0; i<10; i++) {
std::cout << i << "\n";
}
return 0;
}
and why int sret = 1; // value is never used or passed into function
all you want is:
int sret;
sret = testF();
std::cout << sret << "\n";
std::cout << "END\n";
also why doing
sret = testF(),
cout<<sret
this will just append 0 to your output,
instead call testF() directly.
for (int i; i<10; i++) {
This loop tries to read from an uninitialised int. That's undefined behaviour, which means everything can happen and that the program may behave strangely.
What probably happens here in practice is that the memory location of the uninitialised variable contains some random data which is interpreted as something greater than 10, and that the random data is somehow affected by the previous std::cout statement. But that's just guessing; the C++ language simply does not define how your program behaves.
In order to avoid undefined behaviour, you must initialise the variable:
for (int i = 0; i<10; i++) {
By the way...
int sret = 1;
sret = testF();
std::cout << sret << "\n";
This can be written more concisely as:
std::cout << testF() << "\n";
Related
Why do I have a memory fault in the below code? How do I fix it?
I want to read the progress of the outside function.
But I only get the output get_report_progress:100
#include <iostream>
int* int_get_progress = 0;
void get_progress(int* int_get_progress)
{
int n = 100;
int *report_progress = &n;
int_get_progress = report_progress;
std::cout << "get_report_progress:" << *int_get_progress <<std::endl;
}
int main()
{
get_progress(int_get_progress);
std::cout << "main get process:" << *int_get_progress << std::endl;
return 0;
}
Your global int_get_progress variable is a pointer that is initialized to null. You are passing it by value to the function, so a copy of it is made. As such, any new value the function assigns to that pointer is to the copy, not to the original. Thus, the global int_get_progress variable is left unchanged, and main() ends up deferencing a null pointer, which is undefined behavior and in this case is causing a memory fault.
Even if you fix the code to let the function update the caller's pointer, your code would still fail to work properly, because you are setting the pointer to point at a local variable that goes out of scope when the function exits, thus you would leave the pointer dangling, pointing at invalid memory, which is also undefined behavior when that pointer is then dereferenced.
Your global variable (which doesn't need to be global) should not be a pointer at all, but it can be passed around by pointer, eg:
#include <iostream>
void get_progress(int* p_progress)
{
int n = 100;
*p_progress = n;
std::cout << "get_report_progress:" << *p_progress << std::endl;
}
int main()
{
int progress = 0;
get_progress(&progress);
std::cout << "main get process:" << progress << std::endl;
return 0;
}
Alternatively, pass it by reference instead, eg:
#include <iostream>
void get_progress(int& ref_progress)
{
int n = 100;
ref_progress = n;
std::cout << "get_report_progress:" << ref_progress << std::endl;
}
int main()
{
int progress = 0;
get_progress(progress);
std::cout << "main get process:" << progress << std::endl;
return 0;
}
Alternatively, don't pass it around by parameter at all, but return it instead, eg:
#include <iostream>
int get_progress()
{
int n = 100;
std::cout << "get_report_progress:" << n << std::endl;
return n;
}
int main()
{
int progress = get_progress();
std::cout << "main get process:" << progress << std::endl;
return 0;
}
I'm messing around with multithreading in c++ and here is my code:
#include <iostream>
#include <vector>
#include <string>
#include <thread>
void read(int i);
bool isThreadEnabled;
std::thread threads[100];
int main()
{
isThreadEnabled = true; // I change this to compare the threaded vs non threaded method
if (isThreadEnabled)
{
for (int i = 0;i < 100;i++) //this for loop is what I'm confused about
{
threads[i] = std::thread(read,i);
}
for (int i = 0; i < 100; i++)
{
threads[i].join();
}
}
else
{
for (int i = 0; i < 100; i++)
{
read(i);
}
}
}
void read(int i)
{
int w = 0;
while (true) // wasting cpu cycles to actually see the difference between the threaded and non threaded
{
++w;
if (w == 100000000) break;
}
std::cout << i << std::endl;
}
in the for loop that uses threads the console prints values in a random order ex(5,40,26...) which is expected and totally fine since threads don't run in the same order as they were initiated...
but what confuses me is that the values printed are sometimes more than the maximum value that int i can reach (which is 100), values like 8000,2032,274... are also printed to the console even though i will never reach that number, I don't understand why ?
This line:
std::cout << i << std::endl;
is actually equivalent to
std::cout << i;
std::cout << std::endl;
And thus while thread safe (meaning there's no undefined behaviour), the order of execution is undefined. Given two threads the following execution is possible:
T20: std::cout << 20
T32: std::cout << 32
T20: std::cout << std::endl
T32: std::cout << std::endl
which results in 2032 in console (glued numbers) and an empty line.
The simplest (not necessarily the best) fix for that is to wrap this line with a shared mutex:
{
std::lock_guard lg { mutex };
std::cout << i << std::endl;
}
(the brackets for a separate scope are not needed if the std::cout << i << std::endl; is the last line in the function)
I am building a 2d game and I am storing all my enemy objects in an array. Right now I am trying to implement a quadtree. Currently I am just trying to build the quadtree and am not concerned with collisions. The code that pushes items to the quadtree is the following :
for (std::vector<Enemy>::iterator i=m_enemies.begin(); i != m_enemies.end(); ++i) {
std::cout << &(*i) << "Address of the object" << std::endl;
m_quad.Insert(&(*i));
}
The code for the Insert is the following :
void Quad::Insert(sf::RectangleShape* l_gameObject){
std::cout << &l_gameObject << "dsa1" << std::endl;
std::cout << "called insert " << m_objects.size() << std::endl;
m_objects.push_back(l_gameObject);
if (m_level < m_maxLevel) {
if (m_objects.size() > 3) {
std::cout<< "creating subregions " << m_objects.size() << std::endl;
m_subRegions.push_back(Quad(m_x,m_y,m_width/2.f, m_height/2, m_level + 1, m_maxLevel-1));
m_subRegions.push_back(Quad(m_x+m_width/2.f,m_y,m_width/2.f,m_height/2.f, m_level + 1, m_maxLevel-1));
m_subRegions.push_back(Quad(m_x+m_width/2.f, m_y + m_height/2.f, m_width/2.f, m_height/2.f, m_level + 1, m_maxLevel-1));
m_subRegions.push_back(Quad(m_x, m_y + m_height/2.f, m_width/2.f, m_height/2.f, m_level + 1, m_maxLevel-1));
std::vector<int> temp;
for (int i=0; i < m_objects.size(); i++){
for (int j=0; j< m_subRegions.size(); j++) {
if (m_subRegions[j].Contains(m_objects[i])) {
m_subRegions[j].Insert(m_objects[i]);
temp.push_back(i);
break;
}
}
}
for (int i = temp.size(); i > -1; i--){
m_objects.erase(m_objects.begin() + temp[i]);
}
}
}
}
When I print the address that I am passing to the Insert function and the one I have in the function I see that they are different. In fact the on in is always the same and the one I pass is always different as it should be. Could anyone clarify why that is the case ?
EDIT : Thanks to gsamaras for pointing out that I was printing the address of the parameter.
Followup question
When I use the methods of the object I am addressing in the first for loop I get the correct results, but when I do the same thing in the Insert function I get 0. Why is that ?
You are printing the address of the address.
Change this:
std::cout << &l_gameObject << "dsa1" << std::endl;
to this:
std::cout << l_gameObject << "dsa1" << std::endl;
in order to print the same thing as outside your of your function.
Inside Insert, you're printing the address of the parameter.
Outside Insert, you're printing the parameter's value.
You want
std::cout << l_gameObject << "dsa1" << std::endl;
since l_gameObject is the address you're passing in.
I have this:
std::vector <sf::VideoMode> *screenResolution = new std::vector<sf::VideoMode>;
*screenResolution = sf::VideoMode::getFullscreenModes();
for (std::size_t i = 0; i < screenResolution->size(); ++i)
{
std::cout << screenResolution[i]->width << ":" << screenResolution[i]->height <<std::endl;
}
And for some reason an error appears in the cout that says "the expresion must be a type of pointer".
You have to carefuly read error message. Your vector is of sf::VideoMode which doesn't look like pointer. Only -> can dereference pointers, so you can't use it in your loop. You also probably don't need dynamic allocation for your vector.
The following code should work for you:
std::vector<sf::VideoMode> screenResolution = sf::VideoMode::getFullscreenModes();
for (std::size_t i = 0; i < screenResolution.size(); ++i)
{
std::cout << screenResolution[i].width << ":" << screenResolution[i].height << std::endl;
}
#include <iostream>
void swap(int &pi, int &pj){
std::cout << "In function swap: " << &pi << " " << &pj << "\n";
int temp = pi;
pi = pj;
pj = temp;
}
int main(){
int i = 10, j = 20;
int *pi = &i, *pj = &j;
swap(pi, pj);
std::cout << *pi << " " << *pj;
return 0;
}
The above program does not give any compilation error. (Though to swap function in not POINTER TO REFERENCE type) and gives the proper output.
But whatever i am trying to print inside "swap" function is not printed to console.
Can anybody explain me why?
Looks like you're probably using std::swap to swap two pointers instead of calling your own swap routine. I suspect you have a using namespace std; somewhere that you are not showing us ? Try changing the name of your swap routine to e.g. my_swap and then see if calling my_swap works (it should fail with a compilation error).
If you can compile your program, you don't show us all of your code.
This code snippet you posted doesn't compile, because you're trying to pass to objects of type int* to your function swapm which expects a reference to an int.
If your code compiles, I suspect you to include a 'using namespace std;' anywhere in your original code.
you're trying to get the address of a pointer that you're passing by reference... I don't think you quite understand what you're doing. the pass by reference feature in C++ allows you to pass a reference, so you don't need a pointer. Your code should look like this.
#include <iostream>
void swap(int &i, int &j){
std::cout << "In function swap: " << i << " " << j << "\n";
int temp = i;
i = j;
j = temp;
}
int main(){
int i = 10, j = 20;
swap(i, j);
std::cout << i << " " << j;
return 0;
}