Click to See Complete Forum and Search --> : C++ pointer arithmetic question...


Minime80
02-29-2004, 05:42 PM
Okay, let's say I have an array of objects.

array = new object[100];

Now, if I want to step through the array using pointer arithmetic, can I just say?

array + index;

or do I need to use?

array + (index * sizeof(object));

The other question I have about this is, if I'm assigning an object to an element in the array is it necessary to use a temp to store the location of the element where you're storing the object? I've tried putting the pointer arithmetic in the assignment, but no matter how I do it I get a "non-lvalue in assignment" compile error.

jim mcnamara
02-29-2004, 06:00 PM
array=new object[100];
new ptr *object=array;

for (int in=0;i<100;i++) {
*(object + i) <-- reference the element this way
}

cybertron
02-29-2004, 06:07 PM
I'm not sure about the arithmetic part, but it looks like the reason you can't assign pointer values directly is that you're not dereferencing the pointer before you try to use it. i.e. you need to do *array = x as opposed to array = x (or if you're using arithmetic, something like *(array + 1) = x if that's the correct way to do pointer arithmetic). Otherwise you're trying to assign an object to an address (the pointer). The * tells it to change the thing the pointer points to, not the pointer itself.

I think that *(array + 1) is okay for the arithmetic part, but it should be easy enough to check. Just try it and if you get garbage back, then it's wrong.

Come to think of it, I'm not sure you can access an array through pointers. I think it works the other way (you can access pointers using [] subscripts), but not the way you're trying to do it. I think you have to create a new pointer that points to the array. Like this:

array = new object[100];
*arrptr = &array;

I could be wrong though, so someone correct me if I am.

Edit: jim puts it much more succinctly :)

Minime80
02-29-2004, 06:38 PM
Okay, now how would that change if I had an array of pointers to these objects for dynamic allocation.

I'm guessing something like:
array = new object * [100];

// and to allocate a particular element
*(array + index) = new object;

// and to reference a particular element
**(array + index)

// and if that object has member functions
(*(array + index))->function();


How's that look to all of you. I'm just trying to understand this whole pointer arithmetic idea. Let me know if I screwed anything up. Thanks guys.