need help with pointers and how to call a function with pointer name

Some reason my code wont run correctly, and i think there is a problem. Im not entirely sure if i call this function correctly. Any help is appreciated
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
#include<iostream>
using namespace std;

int *gcd(int a, int b);

int main()
{
	int a1, b1;
	
	cout << *gcd(a1, b1);

}

int *gcd(int a, int b)
{
	int *p;
	int c;
	p = &b;
	while (a != 0) {
		c = a;
		a = b%a;
		b = c;
	}
	return p;

}

	
Why are you using pointers here? The pointer p is pointing to a local variable that will no longer exist after the function has ended, so there is no way you can read the value after the function has returned. Another problem is that you forgot to initialize the variables that you pass to the function.
Last edited on
the function definition was given to me and the question is how to call the function in the main. Sorry if i was misleading. Im trying to figure out the value of p after it is returned and i believe it is 4?
As Peter87 said, p points to undefined memory when gcd exits.

Line 18: p points to the address of b on the stack.
Line 24: When gcd exits, gcd's stack frame is gone (including b). You attempt to return p's value, but p now points to something that no longer exists.

Thanks. So p doesnt points to nothing after all!
Topic archived. No new replies allowed.