Ángel
Ángel

Reputation: 145

If I create a vector on the heap, does that mean I could access it from any other function? How?

This statement creates a vector on the heap:

std::vector<int>* pVector = new std::vector<int>();

So, if I declare it in main() or somewhere, how can I access it in another function? For example:

#include <iostream>
#include <vector>
    
void insert(int value);

int main (){
    int n = 1;
    std::vector<int>* pVector = new std::vector<int>();
    insert(n);
    return 0;
}

void insert (int value){
    pVector->push_back(value); //ERROR "was not declared in this scope"
    std::cout << pVector[0] << "\n"; //ERROR
}

I'm learning on my own and heap, pointers and references are being much more complicated than I expected, so any help will be very appreciated.

Upvotes: 1

Views: 160

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 597016

This has nothing to do with heap usage.

pVector is simply a local variable to main(), so only main() can use it. The only way to access the std::vector object from any other function is to explicitly pass in a pointer/reference to it.

You could pass it in using an input parameter, eg:

#include <iostream>
#include <vector>
    
void insert(std::vector<int>& vec, int value);

int main (){
    int n = 1;

    std::vector<int>* pVector = new std::vector<int>();
    insert(*pVector, n);
    ...
    delete pVector;

    /* this works, too:
    std::vector<int> vec;
    insert(vec, n);
    ...
    */

    return 0;
}

void insert (std::vector<int>& vec, int value){
    vec.push_back(value);
    std::cout << vec[0] << "\n";
}

Or, you could use a global variable, eg:

#include <iostream>
#include <vector>
    
std::vector<int>* pVectorToInsertInto;
void insert(int value);

int main (){
    int n = 1;

    std::vector<int>* pVector = new std::vector<int>();
    pVectorToInsertInto = pVector;
    insert(n);
    ...
    delete pVector;

    /* this woks, too:
    std::vector<int> vec;
    pVectorToInsertInto = &vec;
    insert(n);
    ...
    */

    return 0;
}

void insert (int value){
    pVectorToInsertInto->push_back(value);
    std::cout << (*pVectorToInsertInto)[0] << "\n";
}

In general, stay away from using global variables, if you can avoid it.

Upvotes: 2

Related Questions