Can't push into vector using vector pointer

I’m trying to run sieve function and it should return a vector of prime numbers, there’s a problem with the 18th line in code . 18th line isn’t working, it feels as if it’s ignored by the compiler. It doesn’t cause an error neither is it pushing the number in to the vector. This is my code:

#include <bits/stdc++.h>
using namespace std;
#define pb push_back

vector<int>* sieve(int n){
        bool arr[n];
        memset(arr, true, sizeof(arr));
        for(int i=2;i*i<n;i++){
                if(arr[i]){
                        for(int j=i*i;j<n;j+=i){
                                arr[j]=false;
                        }
                }
        }
        vector<int>* primes;
        for(int i=2;i<n;i++){
                if(arr[i]){
                        (*primes).pb(i);//PROBLEM IN THIS LINE
                }
        }

        return primes;
}

int main(){
        vector<int>* primes = sieve();
        for(int el:*primes){
                cout<<el<<endl;
        }
        return 0;
}

I’ve marked the 18th line with a comment //PROBLEM IN THIS LINE

1 Like

primes is an uninitialised pointer, so attempting to do anything with it will cause Undefined Behaviour (most probably, your program crashing or locking up :))

Solution: just use vector<int>'s instead of vector<int>*'s :slight_smile:

3 Likes

Yeah I submitted it with vector, but I’m curious why vector* doesn’t work in my code, because I saw exactly same code written by Sanyam Garg, which seemed to work in his IDE. And I’ve seen many people return pointers to vectors.

You were right, primes was null. Lol silly mistake.
should’ve been vector* primes=new vector();

2 Likes

Are you sure it wasn’t more like this?

#include <bits/stdc++.h>
using namespace std;
#define pb push_back

vector<int>* sieve(int n){
        bool arr[n];
        memset(arr, true, sizeof(arr));
        for(int i=2;i*i<n;i++){
                if(arr[i]){
                        for(int j=i*i;j<n;j+=i){
                                arr[j]=false;
                        }
                }
        }
        vector<int>* primes = new vector<int>(); // <-- Added this.  Will leak memory as is not deleted anywhere!
        for(int i=2;i<n;i++){
                if(arr[i]){
                        (*primes).pb(i);
                }
        }

        return primes;
}

int main(){
        vector<int>* primes = sieve(100);  // <-- And "100" here!
        for(int el:*primes){
                cout<<el<<endl;
        }
        return 0;
}

Edit:

Ah - just saw your edit :slight_smile:

2 Likes