Pointers help

In first code I didn't use
1
2
3
4
5
    string *p_name = &name;
    string *p_surrname = &surrname;

    string& r_name = name;
    string& r_surrname = surrname;

Is this okay?

And is my code written correctly ?


code1
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
27
28
29
30
31
32
33
#include <iostream>
#include <string>


using namespace std;

void p_nameANDsurr (string *name, string *surrname)
{
    cout << *name << " " << *surrname << endl;
}

void r_nameAndSURR (string& name, string& surrname)
{
    cout << name << " " << surrname << endl;
}
int main ()
{
    string name, surrname;



    cout << "Enter name:";
    cin >> name;
    cout << "Enter surrname:";
    cin >> surrname;
    cout << '\n';

    p_nameANDsurr (&surrname, &name);
    cout << '\n';

    r_nameAndSURR (surrname, name);
    cout << '\n';
}

code2
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
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>
#include <string>


using namespace std;

void p_nameANDsurr (string *name, string *surrname)
{
    cout << *name << " " << *surrname << endl;
}

void r_nameAndSURR (string& name, string& surrname)
{
    cout << name << " " << surrname << endl;
}
int main ()
{
    string name, surrname;

    string *p_name = &name;
    string *p_surrname = &surrname;

    string& r_name = name;
    string& r_surrname = surrname;

    cout << "Enter name:";
    cin >> name;
    cout << "Enter surrname:";
    cin >> surrname;
    cout << '\n';

    p_nameANDsurr (p_surrname, p_name);
    cout << '\n';

    r_nameAndSURR (r_surrname, r_name);
    cout << '\n';

    cout << '\n' << *p_name << " " << *p_surrname << endl;
}
Last edited on
Yes. it is correct. I would suggest to start writing const-correct code early and add const [at least] to function parameters which will not change:
1
2
3
void p_nameANDsurr (const string* const name, const string* const surrname)

void r_nameAndSURR (const string& name, const string& surrname)
Topic archived. No new replies allowed.