Results 1 to 5 of 5

Thread: Pointers to arrays

  1. #1

    Thread Starter
    Addicted Member jmiller's Avatar
    Join Date
    Jul 2002
    Location
    University of Michigan
    Posts
    238

    Pointers to arrays

    say i have a function that accepts a pointer like:
    void SomeFunction(Obj *pObj);

    and then i have an array of objects like:
    Obj *myObjects = new Obj[10];

    i know you can pass myObjects and it will be a pointer to the first element, but would it be possible to do this:

    SomeFunction(&myObjects[5]) and thus just have pObj point to element 5 of myObjects?

    thanks

  2. #2
    Fanatic Member riis's Avatar
    Join Date
    Nov 2001
    Posts
    551
    It will work, but this will give a pointer to the sixth object, since arrays are zero-based. I use it quite often for arrays which I don't want to work with sequentially.

  3. #3

    Thread Starter
    Addicted Member jmiller's Avatar
    Join Date
    Jul 2002
    Location
    University of Michigan
    Posts
    238
    okay...
    but let me ask you then, since myObjects[5] is a pointer, wouldn't passing the address of the pointer (&myObjects[5]) pass the address of the pointer itself, and not the address of the myObjects[5] variable?

  4. #4
    Fanatic Member riis's Avatar
    Join Date
    Nov 2001
    Posts
    551

    Re: Pointers to arrays

    Originally posted by jmiller

    Obj *myObjects = new Obj[10];
    You've declared the array as an array of objects, not an array of pointers to objects. So myObjects[5] is an object, not a pointer. Hence &myObjects[5] will pass the address to the object itself.

    If you want to declare myObjects as an array of pointers, then you should do something like this: Obj **myObjects = new Obj*[10]; Then you have to instantiate every object before you can use it: myObjects[0] = new Obj; , etc.
    In the end you have to delete all myObjects[i] and delete[] myObjects itself.

  5. #5
    Kitten CornedBee's Avatar
    Join Date
    Aug 2001
    Location
    In a microchip!
    Posts
    11,594
    Since myObjects[5] is just shorthand for *(myObjects+5) and &myObjects[5] therefore being &*(myObjects+5) you can write myObjects+5 to get a pointer to the 6th elements.

    But the other syntax might be simpler to understand, it's a matter of preference.
    All the buzzt
    CornedBee

    "Writing specifications is like writing a novel. Writing code is like writing poetry."
    - Anonymous, published by Raymond Chen

    Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width