Thread: Pointer question

  1. #1
    Registered User
    Join Date
    Jul 2007
    Posts
    186

    Pointer question

    Hey all,

    If I have a pointer:
    SomeObject *pointer;

    and I want to access a method from that objects class, I would do it via pointer->someMethod.

    However if I say that pointer = new SomeObject[numelements]; then when I want to do pointer[index]->someMethod it fails but pointer[index].someMethod works. I'm new to C++ so I'm not sure why this is the case.

    Thanks
    Last edited by jcafaro10; 03-04-2009 at 06:16 PM.

  2. #2
    Kiss the monkey. CodeMonkey's Avatar
    Join Date
    Sep 2001
    Posts
    937
    [] dereferences (did I spell that right?). That means [] takes pointers to what-they-point-to.

    ptr+1 is a pointer.
    *(ptr+1) is some type.
    ptr[1] is the same as *(ptr+1).

    we use -> for pointers and . for regular stuff.
    "If you tell the truth, you don't have to remember anything"
    -Mark Twain

  3. #3
    Registered User
    Join Date
    Dec 2007
    Posts
    930
    pointer[index]->someMethod is equal to *(pointer[index]).someMethod but since pointer[index] is an array you dont need the "*" sign.
    If it wasnt an array like *(pointer).someMethod, this pointer->someMethod would work.

    An array is already like a pointer thats why you dont need the dereferencing sign.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. sorting number
    By Leslie in forum C Programming
    Replies: 8
    Last Post: 05-20-2009, 04:23 AM
  2. Easy pointer question
    By Edo in forum C++ Programming
    Replies: 3
    Last Post: 01-19-2009, 10:54 AM
  3. char pointer to pointer question
    By Salt Shaker in forum C Programming
    Replies: 3
    Last Post: 01-10-2009, 11:59 AM
  4. Pointer question
    By rakan in forum C++ Programming
    Replies: 2
    Last Post: 11-19-2006, 02:23 AM
  5. pointers
    By InvariantLoop in forum C Programming
    Replies: 13
    Last Post: 02-04-2005, 09:32 AM