std-method

Advance within a single array with add

add advances in units of the pointee type, not bytes. For this nonzero-sized array, the pointer and result must be within the same allocation or at its one-past boundary, and the offset must satisfy the signed byte-distance restriction. A one-past pointer is not an element to read. Expected stdout (not executed): 30 Common mistake: Calling add on an out-of-bounds offset even if the result is never read.

Formal Syntax & Structure

rust syntaxrust
unsafe { p.add(count) }

Working Example

Example Snippetrust
#![deny(unsafe_op_in_unsafe_fn)]fn main() {    let items = [10_u32, 20, 30];    let p = items.as_ptr();    // SAFETY: index 2 is within this initialized array; the offset is small.    let third = unsafe { *p.add(2) };    // SAFETY: exactly one past the same live array; no access there.    let _end = unsafe { p.add(items.len()) };    println!("{third}");}
Rust Reference