Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using explicit/raw pointers in c++

Tags:

c++

pointers

I read that using raw pointers in C++ is bad. Instead we should use auto_ptr. In the below code I am populating a vector in foo() that is created in the main(). Am I doing it right or is there a better way to do without using explicit pointers.

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

using namespace std;

void foo(vector<string> *v){

    (*v).push_back(" hru");
}

int main(){
    vector<string> v;
    v.push_back("hi");
    foo(&v);
    for(int i=0;i<v.size(); i++){
        cout << v[i];
    }

}
like image 343
FourOfAKind Avatar asked Sep 13 '26 13:09

FourOfAKind


2 Answers

C++ uses references for what you are trying to do:

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

using namespace std;

void foo(vector<string>& v){
    v.push_back(" hru");
}

int main(){
    vector<string> v;
    v.push_back("hi");
    foo(v);
    for(int i=0;i<v.size(); i++){
        cout << v[i];
    }
}

References and pointers are similar, with one very important distinction: there is no such thing as a null reference (Constructing one is Undefined Behavior in C++ you can construct one, but doing so is considered a hack).

like image 55
Sergey Kalinichenko Avatar answered Sep 16 '26 05:09

Sergey Kalinichenko


In C++ you can avoid the pointer and use a pass-by-reference:

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

using namespace std;

void foo(vector<string>& v){

    v.push_back(" hru");
}

int main(){
    vector<string> v;
    v.push_back("hi");
    foo(v);
    for(int i=0;i<v.size(); i++){
        cout << v[i];
    }    
}
like image 25
Tudor Avatar answered Sep 16 '26 04:09

Tudor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!