anna anna - 1 year ago 69
C++ Question

Issue finding size of dynamic int array that contains a zero

We are not allowed to use vectors.

Another noobie with a problem. I am trying to find the index of a dynamic int array that is initialized to a size of 50. We can only use a dynamic int array.

Say for example I’m only entering 10 integers into this array: 1 9 5 3 8 0 8 2 0 6

The rest of the array is NULL. The goal is to keep the integer values that were entered into this array and put them into an output file. So the size of the array of ints I want is 9. But when I do the following:

int index = 0;

while (intArray[index])

It tells me that the index is 5 and thus only 5 values get copied into the output file. I know it’s because of the 0 in the array. If there is no 0 in the array, the results come out as expected. How do I bypass this so that the index is correctly reflected as 9 and all the values get copied properly? I appreciate any input!

Answer Source

There is no such thing as NULL for integer value. So there are 3 usual approaches, that used:

  1. Special value, marker of the end. This aproach is used for C-style strings, where '\0' used as end. For integer this approach will not work as 0 is "normal" value. You may use some other special value, like std::numeric_limits<int>::min or std::numeric_limits<int>::max, but this would be not very good approach.
  2. Have another variable, that holds current size of array. Note this is usually different, than for how many elements were allocated. This could be wrapped into a class. This is how std::vector is implemented.
  3. Have another variable, pointer, that points to the pone element after the last one. This could be useful for using in standard algorithms.

Approach 2 and 3 are very close and one can be converted very easy to another. So I would recommend to rewrite your algorithm using start and behind_end iterator:

auto end = myArray + 5; // 5 elements in array
for( auto it = myArray; it != end; ++it ) {
    std::cout << *it << endl;

this code can be easily templatized and used with standard containers.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download