Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does pointer arithmetic have uses outside of arrays?

Tags:

c++

c

I think I understand the semantics of pointer arithmetic fairly well, but I only ever see examples when dealing with arrays. Does it have any other uses that can't be achieved by less opaque means? I'm sure you could find a way with clever casting to use it to access members of a struct, but I'm not sure why you'd bother. I'm mostly interested in C, but I'll tag with C++ because the answer probably applies there too.

Edit, based on answers received so far: I know pointers can be used in many non-array contexts. I'm specifically wondering about arithmetic on pointers, e.g. incrementing, taking a difference, etc.

like image 340
Shea Levy Avatar asked Sep 28 '11 00:09

Shea Levy


People also ask

What is pointer arithmetic used for?

We can perform arithmetic operations on the pointers like addition, subtraction, etc. However, as we know that pointer contains the address, the result of an arithmetic operation performed on the pointer will also be a pointer if the other operand is of type integer.

Which operations is allowed in pointer arithmetic?

You can perform a limited number of arithmetic operations on pointers. These operations are: Increment and decrement. Addition and subtraction.

Is pointer arithmetic faster than array indexing?

Pointer arithmetic is slightly faster (about %10) than array indexing.


1 Answers

Pointer arithmetic by definition in C happens only on arrays. However, as every object has a representation consisting of an overlaid unsigned char [sizeof object] array, it's also valid to perform pointer arithmetic on this representation. For example:

struct foo {
    int a, b, c;
} bar;

/* Equivalent to: bar.c = 1; */
*(int *)((unsigned char *)&bar + offsetof(struct foo, c)) = 1;

Actually char * would work just as well.

like image 171
R.. GitHub STOP HELPING ICE Avatar answered Sep 22 '22 15:09

R.. GitHub STOP HELPING ICE