devork

E pur si muove

Pointer arithmetic in C

Monday, January 25, 2010

Pointer arithmetic in C is great. The only downside is that it's only defined when pointing to an array (or an item just after the array). That is one giant downside.

Allocate a chunk of memory and you can't use pointer arithmetic. So if you are building a linked list this means you will have to allocate each item in the list separately, even if you know the total length the list will ever have.

Even K&R must have realised this was an annoying limitation. They point this out when they show how to write malloc (K&R2 8.7 Example -- A Storage Allocator)

There is still one assumption, however, that pointers to different blocks returned by sbrk can be meaningfully compared. This is not guaranteed by the standard, which permits pointer comparisons only within an array. Thus this version of malloc is portable only among machines for which general pointer comparison is meaningful.

If only the standard would have relaxed this restriction slightly (e.g. to continuously allocated regions) life would be so much better

Monday, January 25, 2010 |

0 comments:

New comments are not allowed.

Subscribe to: Post Comments (Atom)