pointers to structs vs -> to structs

Personal contribution.

Just to show that for example (*p).x and p -> x can be used for the same purposes proving that they give the same output.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// Example program
#include <iostream>
using namespace std;

struct test{
 double x,y;   
};

int main()
{
    test* p = new test {3.14, -6.28};
    
    //using (*p).dataName;
    cout << "x: " << (*p).x << endl;
    cout << "y: " << (*p).y << endl;
    
    cout << endl;
    
    // using -> notation:
    cout << "x: " << p->x << endl;
    cout << "y: " << p->y << endl;
    
    return 0;
}




x: 3.14
y: -6.28

x: 3.14
y: -6.28
 
delete p
We all know the basic stuff. Is it your new invention or something?
@Yatora: this site is to encourage folks to learn, if you think it's "basic" you can just keep quiet.
OP - another alternative would be to use std::unique_ptr in which case you don't have to delete:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <memory>
using std::cout; using std::endl;

struct test{
 double x,y;
 test(const double& X, const double& Y)
 : x(X), y(Y){}
};

int main()
{
    auto p (std::make_unique<test> (3.14, -6.28));

    //using (*p).dataName;
    cout << "x: " << (*p).x << endl;
    cout << "y: " << (*p).y << endl;

    cout << endl;

    // using -> notation:
    cout << "x: " << p->x << endl;
    cout << "y: " << p->y << endl;

    return 0;
}

Topic archived. No new replies allowed.