0

How can I allocate a vector by reference? The issue is that the pointer in the foo function does not return by reference as being allocated.

#include <iostream>
#include <vector>
#include <string>



void foo(std::vector<std::string>*ss) {
    if (ss == nullptr) {
        ss = new std::vector<std::string>();
    }
}

void add(std::vector<std::string> *ss) {
    ss->push_back("test");
    ss->push_back("test1");
    ss->push_back("test2");
    ss->push_back("test3");
    ss->push_back("test4");
}

int main(void) {
    std::vector<std::string> *ss = nullptr;

    foo(ss); //Does not get new vector
    add(ss); //seg fault because still nullptr 
    for (auto i : *ss) {
        std::cout << i << "\n";
    }
    ss->clear();
    delete ss; ss = nullptr;
    return 0;
}
boardkeystown
  • 180
  • 1
  • 11
  • 1
    `void foo(std::vector*&ss) {` – πάντα ῥεῖ Mar 15 '22 at 00:10
  • Ohhhhhh. Wait. Can you explain why that works? It's a * (pointer) of a & (address) so you can pass it a pointer? To me that is weird since I normally don't do it like this. – boardkeystown Mar 15 '22 at 00:16
  • 1
    @πάνταῥεῖ In what way is this question "not reproducible" or "caused by a typo"? Please try and use appropriate close reasons. Especially when the question is an obvious dupe, and you can use your hammer single-handedly. – cigien Mar 15 '22 at 00:23
  • 2
    @boardkeystown Many symbols in c++ have multiple meanings, which depends on the context. In `std::vector*&ss` the `&` symbol is not the "address of" operator. It indicates a reference type. See [What is definition of reference type](https://stackoverflow.com/questions/24827592/what-is-definition-of-reference-type). – François Andrieux Mar 15 '22 at 00:54
  • 1
    `std::vector*&ss` does not specify a pointer of an address. It's a reference to a pointer. – Peter Mar 15 '22 at 01:59

0 Answers0