user1311627
user1311627

Reputation: 261

Proper way to mark the end of an array

I only have access to an array and not a vector.

Say I might need an array of 100 objects but it could be less. If it is less is there an elegant way of marking this point so that its known that the rest of the objects are not required?

Or do I have to store this in the object itself? Is there no equivalent of a null character?

Upvotes: 2

Views: 1295

Answers (2)

Pete Becker
Pete Becker

Reputation: 76448

There are several possible approaches.

You can use a sentinel value, and put that value at the end of the array, much like '\0' marks the end of a C-style string. The problem with that is that you have to be sure that your sentinel value will never occur in the data that you need to store.

You can carry around a count of the number of values in the array, and pass that value to functions that deal with your array.

You can create a pointer that points one past the last element in the array, and deal with the array as a pair of pointers: one that points at the first element, and one that points one past the end. That's compatible with STL algorithms, so it's probably your best overall approach.

Upvotes: 3

Sam Varshavchik
Sam Varshavchik

Reputation: 118445

No, there's nothing that marks the end of an array in memory. There is "no equivalent of a null character". It is your responsibility to keep track of this.

One of the many reasons for using a std::vector is that the vector keeps track of this. But since, as you stated, you "have access to an array and not a vector", then it's up to you to handle the vector's responsibilities.

Upvotes: 0

Related Questions