Archived

This topic is now archived and is closed to further replies.

PuterPaul

What effect does the following have

Recommended Posts

I''m having a little bit of trouble understanding what effect the following would have in C++.
// where oldByteArray is a byte* and offset is an int

byte * byteArray = oldByteArray + offset;
Does it create a new array that is the size of oldByteArray + offset?????

Share this post


Link to post
Share on other sites
that line actually just creates a pointer, which instead of pointing to the beginning of oldByteArray, points to some element in the old array which is "offset" bytes into the array.

The fundamental concept here is pointer arithmetic. Essentially, all pointers are simply numbers (you can think of them as integers, but their maximum size will depend on the architecture you're compiling for). When you create a pointer and assign it to some address, that pointer's value is just a number representing a location in your memory store.

Simply adding 1 to a pointer will move it forward by however large the pointer's representation is. Since the byteArray pointer is of type byte* then moving it forward will move the pointer in increments of byte. If someArray were of type MyObject* then moving it forward would move the pointer in increments of sizeof(MyObject).

You need to be careful that when you use pointer arithmetic you don't go outside of the bounds of the memory you have allocated. If you're lucky you'll get a segmentation fault. Sometimes, though, you can end up altering data in other parts of your code and this will leave you scratching your head for quite some time.

[edited by - void* on April 4, 2004 1:32:46 PM]

Share this post


Link to post
Share on other sites
Ok bear with me i think i''m starting to get this now so if I had the following.


//where lookup is byte* and lower is int

byte* l = lookup+lower
for(int i=lower;i<upper;i++)
*l++=((i-wl)*maxval)/ww+maxval/2;


Would be the same as the following in java???

for(int i=lower;i<upper;i++)
lookup[lower++]=((i-wl)*maxval)/ww+maxval/2;

Share this post


Link to post
Share on other sites
Try this less-mangled and more easily readable code instead, dude..


byte* k = lookup + lower;
for( int i = lower; i < upper; i++ )
*(k++) = (((i - wl) * maxval) / ww) + (maxval / 2);

// And in Java...

for( int i = lower; i < upper; i++ )
lookup[i] = (((i - wl) * maxval) / ww) + (maxval / 2);

Code is easier to read and understand when you go without pointers when you can, and go with pointers when the usage of them is clear. The first code segment uses a pointer and moves it along the lookup array; do this only when you''ll need that pointer for some operation later on. The second code segment uses an integer to do the same work, and in fact that second code segment will work the exact same in C, C++, or Java. Just copy&paste into an appropriate sourcefile.

Share this post


Link to post
Share on other sites