0

So say you have an array (ex. array[1000]). 1000 values can go into this but there does not have to be that many. In that case I would not want to loop through all 1000 values, so how does one loop through until a blank index is reached?

Tyler Small
  • 85
  • 11
  • 1
    What do you mean by a "blank index"? – 3442 Nov 14 '15 at 06:47
  • 2
    Your best bet is to use [std::vector](http://www.cplusplus.com/reference/vector/vector/) instead of an array :) – paulsm4 Nov 14 '15 at 06:47
  • If you want to gain performance and still get all the convenience from standard containers, you can try to use stack allocator http://stackoverflow.com/questions/354442/looking-for-c-stl-like-vector-class-but-using-stack-storage – Vitalii Minnakhmetov Nov 14 '15 at 07:07
  • An array always has exactly as many elements as it is declared with, not at most that many elements. – Ulrich Eckhardt Nov 14 '15 at 07:51

3 Answers3

1

There are 3 possibilities:

1) as Murat described use a variable to store the position of the last element. (there is no such thing in the std you have to store it yourself)

2) use a Special value to mark empty the end eg nullptr for pointers then your Code would look like this:

for(int i=0 ;  i<1000 && Array[i] != nullptr ; i++)

for double you could use DBL_MAX etc.

3) Recommended: dont use an Array: use something like std::vector. A vector can hold as many values you need and can be resized

  • edited out an error: i<1000 should be evaluated before Array[i]. This utilizes lazy evaluation in order to make sure that you dont move out of bounds. – Matthias Lupberger Nov 16 '15 at 07:14
0

You can use Last_Element variable which stores the last element of the array you are using. In a for loop, go through Last_Element. When making a update on array maximize the Last_Element variable.

Murat Akburak
  • 51
  • 1
  • 1
  • 12
0

Create a variable that keeps a count with how many "useful" values are in your array. E.g., the variable counter. Then everytime you want to add a new value, you will add it on position counter and then increment counter by 1.

#include <stdio.h>

int addValue(int value, int* array, int counter) {
    array[counter]=value;
    return counter+1;
}

void printArray(int* array, int counter) {
    int k;
    printf("The array has %d elements:\n",counter);
    for(k=0;k<counter;k++)
        printf("\tElement %d -> %d\n",k,array[k]);
}

int main() {
    int array[1000];
    int counter = 0;
    counter = addValue(10,array,counter);
    counter = addValue(3,array,counter);
    counter = addValue(-6,array,counter);

    printArray(array,counter);

    return 0;
}