Thread: What's wrong with this (pointers)

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    Code:
        for(int i =0; i<10; i++)
        {
            cout <<a<<"\n";
            *b++; //shouldn't this assigned a new value to a??
        }
    the post increment operater will be executed first -> first the pointer is incremented pointing to the next int in memory and that is dereferenced

    you want (*b)++

    Kurt

  2. #2
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Quote Originally Posted by ZuK View Post
    the post increment operater will be executed first -> first the pointer is incremented pointing to the next int in memory and that is dereferenced
    That's not exactly correct. The expression b++ has the effect of incrementing b, and a result equal to the original value of b. It is then the original value of b that is dereferenced.

    First time through the loop *b++ produces a result equal to a, and increments b. The other times through the loop, however, start with b pointing to a non-existant variable (or location in memory). So dereferencing produces undefined behaviour (and the increment causes b to walk through memory that, as far as the program is concerned, does not exist).
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Something wrong with pointers
    By serg_yegi in forum C Programming
    Replies: 3
    Last Post: 03-26-2010, 06:38 PM
  2. Replies: 6
    Last Post: 06-16-2008, 04:06 AM
  3. Replies: 9
    Last Post: 07-15-2004, 03:30 PM
  4. Passing variables by pointers...what am I doing wrong?
    By Shadow12345 in forum C++ Programming
    Replies: 2
    Last Post: 06-07-2002, 02:10 PM
  5. Replies: 1
    Last Post: 01-20-2002, 11:50 AM