Slice Pointer

Are a and b the same way to declare a slice pointer?

\\ One way to declare a slice pointer
var a = [*]u8;

\\ Another way to declare a slice pointer
var b = *[]u8;

a is a many-item pointer to a slice of bytes, which means it has no information about the slice length.

b is a pointer to a slice of bytes, which does have information about the slice length.

See the langref’s Pointers section.

6 Likes

I wouldn’t call a a slice pointer, just a regular pointer. Zig makes a distinction between pointers that point to a single item and pointers that may point to multiple items, hence the [*] syntax, but in a language like C they would be the same. However b is a pointer to a slice. Some notable differences between the two:

  • You need two dereference operations to access an element in b, while for a you only do one dereference.
  • b.* carries information about the length of the pointed-at slice, while a does not track length of any kind.
5 Likes

I think it would also help to note that a slice []T is basically a struct{ptr: [*]T, len: usize} with some syntactic sugar added to it. If you substitute that into your example you get:

var a = [*]u8;
var b = *struct{ptr: [*]u8, len: usize};

Now those are clearly different things.

6 Likes

Thanks for all the responses. I get it now. Thanks

@kyp0717 Glad you could find some assistance! Don’t forget to mark the solution you think that best solves your question for future users :slight_smile: