Pointer Artithmetic Puzzle

C

charlie

Hi,
I just came across this issue in my code and, while it isn't an issue
any more because the whole algorithm had to be changed, it is still
bothering me because I don't understand why it should be so.

I am using a struct type that has some data as well as prev and next
pointers to implement linked list functionality.
I pre-allocate a block of structs (called fieldIndex)
malloc(n * sizeof(fieldIndex));
and then arrange the pointers internally to be consistent.
Then later on I want to find out if the current prev pointer is in the
same block. To start with I used:
current->prev == current - 1
thinking that pointer arithmetic would be invoked and all would be
well. It wasn't so I tried this:
current->prev == current - sizeof(fieldIndex)
and it worked just fine.
I use pointer arithmetic quite a bit and I cannot explain why I have to
invoke sizeof in this case. I looked at K&R and I couldn't see anything
that would suggest a difference between assignment and comparison
operations or any other rule for this case but I couldn't see anything.
I also tested under gcc and MSVC it is consistent, fyi.
Can anyone shed any light on this?

Cheers,
Charlie.
 
C

charlie

Ok so I'm an idiot and there is another bug that's causing this not to
work but making it appear that pointer arithmetic is the problem argh!
At some point I will learn to wait an hour or so to post to usenet then
I won't have to publiclly call myself an idiot so much!

Cheers,
Charlie
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top