Pointer arithmetic like in C?

Hi,

Does Rust programming language have pointer arithmetic similar to C?

Please comment. Thanks in advance.

Best Regards,

Kaushal

I moved your question to a new topic.

Pointer arithmetic exists in unsafe code when working with raw pointers, but it is generally not used in safe Rust.

Kind of, sort of. You will have to make use of the "unsafe" keyword to do it. It's not required in typical applications programming.

I suspect reading the Rust Book will answer your question better:
https://doc.rust-lang.org/book/

Or see Rust By Example: Unsafe Operations - Rust By Example

Or if you want to get more serious read: " Learn Rust With Entirely Too Many Linked Lists": Introduction - Learning Rust With Entirely Too Many Linked Lists

See add and offset and friends. As you can see, they are themselves unsafe.

Indexing (or iterators) take care of most C use-cases for you; additionally, the default layout of structs is not guaranteed. So while pointer arithmetic may be going on behind the curtain in some cases, the typical Rust program will be working at a safer abstraction layer that uses references and not raw pointers.

1 Like

Typically instead of pointer arithmetic, Rust uses slices and ranges.

buf++;

in Rust is:

buf = &buf[1..];

This has the advantage that slices keep track of their length, and won't let you go past the end.

1 Like