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.
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.