Search code examples
c++visual-c++msvc12

MSVC Debugger tells me that my vector has more positions than specified


I have declared the following:

const int NUMBER_OF_DIGITS = 16;
std::vector<int> digits(NUMBER_OF_DIGITS);

However when I open the MSVC debugger it shows the following:

enter image description here

This is how I added values to the vector:

for (int i = 0; i < NUMBER_OF_DIGITS; ++i) {
        scanf("%d", &digits[i]);
    }

Is this normal? Can I just ignore this? Or is this a problem?

Full code(the program is still not ready yet):

#include <iostream>
#include <vector>
#include "stdio.h"

const int NUMBER_OF_DIGITS = 16;

int checksum, tmp1, tmp2, tmp3, sum = 0;

std::vector<int> digits(NUMBER_OF_DIGITS);
std::vector<int> new_digits(NUMBER_OF_DIGITS);

int luhn_checksum(std::vector<int> cardnumber[NUMBER_OF_DIGITS]) {
    //step 1: duouble every second number
    for (int i = 1; i < NUMBER_OF_DIGITS; i += 2) {
        new_digits[i] = digits[i] * 2;
        if (new_digits[i] > 9) {
            //if the product is larger than 9 we will add the two numbers together
            //example: 9 * 2 = 18 so we will add 1 + 8 to get 9
            tmp1 += new_digits[i] % 10;
            new_digits[i] /= 10;
            tmp1 = 0;
        }
    }

    //step 2: sum all the values
    for (int i = 0; i < NUMBER_OF_DIGITS; ++i) {
        checksum += new_digits[i];
    }

    return checksum;
}

void get_card_numbers(void) {
    for (int i = 0; i < NUMBER_OF_DIGITS; ++i) {
        scanf("%d", &digits[i]);
    }
}

void initialize(void) {
    for (int i = 0; i < NUMBER_OF_DIGITS; ++i) {
        digits.push_back(0);
        new_digits.push_back(0);
    }
}


int main() {
    initialize();

    get_card_numbers();

    printf("checksum is: %d\n", luhn_checksum(&digits));


    std::cout << digits.size() << std::endl;


    int x; scanf("%d", &x);
    return 0;
}

Solution

  • The constructor you're using for digits is setting the size by specifying the count. So after calling push_back you've just added another 16 to the vector. Use a different constructor that doesn't set the count.

    int _tmain(int argc, _TCHAR* argv[])
    {
        const int NUMBER_OF_DIGITS = 16;
    
        std::vector<int> digits(NUMBER_OF_DIGITS);
        //std::vector<int> digits;
    
        int digitsLen = digits.size();
        // Here is 16
    
        for (int i = 0; i < NUMBER_OF_DIGITS; ++i) {
            digits.push_back(0);
        }
    
        int digitsLen2 = digits.size();
        // Here is 32
    
        return 0;
    }