|
-
Jan 10th, 2003, 06:21 PM
#1
Thread Starter
Addicted Member
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
-
Jan 11th, 2003, 05:01 AM
#2
Fanatic Member
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.
-
Jan 12th, 2003, 12:34 AM
#3
Thread Starter
Addicted Member
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?
-
Jan 12th, 2003, 03:15 AM
#4
Fanatic Member
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.
-
Jan 12th, 2003, 10:28 AM
#5
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|