Home > database >  overflow when attempting to push_back randomly generated numbers in a vector
overflow when attempting to push_back randomly generated numbers in a vector

Time:11-27

my code is shown here:

#include <iostream>
#include <vector>
#include <string>
#include <stdlib.h>
using std::string;
using std::endl;
using std::cout;
using std::cin;

struct funcs
{
    std::vector<int> values;
    int sum;
    void createVectorValues(){
        while(values.size() < 100)
        {
            int x = rand() % 100;
            values.push_back(x);
        }
        for(int& a : values)
        {
            sum  = 1;
        }
        cout << sum;

    }
};
int main()
{
    srand;
    funcs myFunct;
    myFunct.createVectorValues();
    
}

the following code results in a large value such as -858993360

How can I change this code so that it can function properly

CodePudding user response:

  1. You didn't define a constructor for funcs, so you get the default constructor, which invokes the default constructor of each member. This means the int member sum is left with an indeterminate value. See Does the default constructor initialize built-in types?. You probably want to write a constructor that initializes sum to 0.

  2. srand; isn't a function call. It's valid syntax, because srand evaluates to a pointer to the srand function, but it's an expression with no side effects, so it does nothing. Much as if you had written 3;. To call the function, you need srand(arg), where arg is an appropriate integer. Or, switch to the C 11 random number generation features, which are much more powerful and usually have better randomness.

CodePudding user response:

Try this:

int main(int, char **) {
    funcs myFunct;
    myFunct.createVectorValues();
}

Although no idea why your antivirus is involved. That might be a separate issue.

  •  Tags:  
  • c
  • Related