Pointer Help

Ok so i'm practicing pointers and I made a small program passing them in the function parameters but when I run it, it crashes, why is that?


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
#include <iostream>
#include <string>

using namespace std;

void SetWinParams(int *width, int *height)
{
    int setWidth = 800;
    int setHeight = 600;

    width = &setWidth;
    height = &setHeight;
}

void GetWinParams(int *width, int *height)
{
    SetWinParams(width, height);

    cout << *width << " " << *height << endl;
}

int main()
{
    int *W;
    int *H;

    GetWinParams(W, H);

    return 0;
}
setWidth and setHeight are local variables, so they are destroyed when SetWinParams returns.
But I thought I was assigning their address to width and height pointers? so If they get destroyed when scope is left then what do i do? make them static?
Last edited on
Ok so I believe i figured it out, but please tell me if i'm wrong this seems to work, I tested it with and without de referencing the pointer and whne i de referenced it i got the numbers and when i didnt de reference it i got memory addresses. I think this is right but I just want to make sure.

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
#include <iostream>
#include <string>

using namespace std;

void SetWinParams(int *&width, int *&height)
{
    int setWidth = 800;
    int setHeight = 600;

    width = &setWidth;
    height = &setHeight;
}

void GetWinParams(int *&width, int *&height)
{
    SetWinParams(width, height);

    cout << width << " " << height << endl;
}

int main()
{
    int *W;
    int *H;

    GetWinParams(W, H);

    return 0;
}


Also

1
2
3
4
int *W;
    int *H;

    GetWinParams(W, H);


are pointers that don't point to anything, they are there solely so that i can have an argument to pass so I can use that function, so do I still need to initialize them? or at least set them to nullptr?
well it's generally wise to initialize variables...

Your code doesn't work. This time it is like Yay295 stated: What width and height points to is invalid.

Consider the following:
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 SetWinParams(int *&width, int *&height)
{
    int setWidth = 800;
    int setHeight = 600;

    *width = &setWidth; // Note: *
    *height = &setHeight; // Note: *
}

void GetWinParams(int *&width, int *&height)
{
int width = 0;
int height = 0;

    SetWinParams(&width, &height);

    cout << width << " " << height << endl;
}

int main()
{
    int *W;
    int *H;

    GetWinParams(W, H);

    return 0;
}


By the way: Your original code crashed because the access to invalid pointer in GetWinParams(...)
Last edited on
Topic archived. No new replies allowed.