0

I am trying to get my head around pointers and cant understand why using the dereference operator to print a value works fine when "\n"; is added to the line, but for some reason I dont get any output when I use endl;. The terminal shows no output with endl;. Is this something to do with output buffer flushing?

#include <iostream>
using namespace std;

int main()
{
    int arrayA[] = {0, 1, 2, 3, 4, 5};
    int * ptr_P;

    ptr_P = arrayA;
    for (int i; i < 6; i++)
    {
        cout << *ptr_P << "\n"; // Works fine, but endl; does not
        ptr_P++;
    }
   return(0);
}
Community
  • 1
  • 1
kezzos
  • 3,023
  • 3
  • 20
  • 37
  • It works for me with endl... there is no reason it wouldn't. Are you sure you rebuilt the program properly? – onqtam Jun 05 '15 at 10:35
  • Can't believe it. The only scenario where endl is not working is when endl is redefined to something else. So please try to not use `using namespace std` and replace `endl` with `std::endl` – Klaus Jun 05 '15 at 10:37
  • Just replacing "\n" with endl. I am using Netbeans 8. That is my whole program above. std::endl didnt fix the issue. So confused – kezzos Jun 05 '15 at 10:37
  • Often you don't really need `std::endl`, just writing `'\n'` for the end-of-line, and flush only when really needed. And remember that output streams are flushed when the stream is closed, which happens when the program exits. – Some programmer dude Jun 05 '15 at 10:39
  • If I type make testprogam in a terminal and then ./testprogram I still get nothing.. – kezzos Jun 05 '15 at 10:40

1 Answers1

5

You are not initialising i:

for (int i; i < 6; i++)

This should be:

for (int i = 0; i < 6; i++)

otherwise you have undefined behaviour and your loop may not execute at all.


Note that any good compiler with suitable warnings enabled would have pointed out this mistake to you and saved you some time and effort:
main.cpp: In function 'int main()':
main.cpp:10:14: warning: 'i' may be used uninitialized in this function [-Wmaybe-uninitialized]
     for (int i; i < 6; i++)
              ^
Paul R
  • 208,748
  • 37
  • 389
  • 560