Am i doing pointers correctly?

I bought Sams Teach yourself C++ in 24 hours which is awesome and Im learning things very well, but i want to make sure i know the concept of basic pointers, and if you spot anything wrong or that can be done bettwer in my simple pointer program please let me know.

This all compiles and works correctly displaying the correct values.

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>

using namespace std;

void pToFunction(int pntr1)
{
    cout << pntr1 << endl;
}

int pFromFunction()
{
    int number = 900;
    int *pNumber = &number;

    return *pNumber; //Want to de-reference before returning
}

//Also can do this?

void pFromFunction2(int pntr2)
{
    int number = 30;
    int *pNumber = &number;

    cout << *pNumber << endl;
}

int main()
{
    int age = 50;
    int *pAge = &age;
    int pNumber = 0;

    pToFunction(*pAge);

    cout << pFromFunction() << endl;

    pFromFunction2(pNumber);
}
Last edited on
I do not see any sense in the code. For example function pFromFunction2 is declared as having a parameter. But this parameter is not used. What is the sense in this call?!

pFromFunction2(pNumber);
oh ok sorry i was trying to do something else with that but went another way, ok i removed the parameters from that. I was trying to pass by reference with that one. Here is the updated code of what i was trying to do with that last one:

This is just a test project but does everything look ok?

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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <iostream>

using namespace std;

void pToFunction(int pntr1)
{
    cout << pntr1 << endl;
}

int pFromFunction()
{
    int number = 900;
    int *pNumber = &number;

    return *pNumber;
}

//Also can do this?

void pFromFunction2()
{
    int number = 30;
    int *pNumber = &number;

    cout << *pNumber << endl;
}

//Pass by reference

void pPassByReferenceFunction(int &Num)
{
    int number2 = 30000;
    int *pNumber = &number2;

    Num = *pNumber;
}

int main()
{
    int age = 50;
    int *pAge = &age;
    int pNumber = 0;
    int PBR = 0;

    pToFunction(*pAge);

    cout << pFromFunction() << endl;

    pFromFunction2();

    pPassByReferenceFunction(PBR);

    cout << PBR << endl;
}
Last edited on
bump
Also, pToFuncrion(int) does not take a pointer. If you want it to take a pointer, make its parameter int* and call it this way pToFunction(pAge)

Aceix.
ok
Topic archived. No new replies allowed.