简体   繁体   中英

Check array element for null

I have an array called quint8 block[16] which I:

  • initialize to zero with block[16] = { 0 }
  • fill it with some data
  • then pass it to a method/function as an argument like this bool fill(const quint8 *data)

In this fill function I want to see if the array is filled completely or if it contains null elements that were not filled.

Is it correct to perform a check this way? if(!data[i]) ? I have seen similar Q&A on this forum but all of them use \\0 or NULL and I've heard this is not a good style for doing so and that has confused me.

Integer types do not have a "null" concept in C++.

Two possible ideas are:

1) Use some specific integer value to mean "not set". If 0 is valid for your data, then obviously it cannot be used for this. Maybe some other value would work, such as the maximum for the type (which looks like it would be 0xff in this case). But if all possible values are valid for your data, then this idea won't work.

2) Use some other piece of data to track which values have been set. One way would be an array of bools, each corresponding to a data element. Another way would be a simple count of how many elements have been set to a value (obviously this only works if your data is filled sequentially without any gaps).

If your question is whether you can distinguish between an element of an array that has been assigned the value zero, versus an element that has not been assigned to but was initialized with the value zero, then the answer is: you cannot.

You will have to find some other way to accomplish what you are trying to accomplish. It's hard to offer specific suggestions because I can't see the broader picture of what you're trying to do.

It depends on whether type quint8 has a bool conversion operator or some other conversion operaror for example to an integer type.

If quint8 is some integral type (some typedef for an integral type) then there is no problem. This definition

quint8 block[16] = { 0 };

initializes all elements of the array by zero.

Take into account that in general case the task can be done with algorithms std::find , std::find_if or std::any_of declared in header <algorithm>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM