I'm a beginner programmer and I'm learning my first language, C.
I'm learning mostly from Deitel and Deitel's C How to Program book, but also using example tasks and things from the university, however I am stuck on one.
I have a very very basic understanding of pointers - adding & in front of a variable makes it print an address and * uses a pointer to use the value stored at that address or such.
The piece of code I've written is for calculating the greatest (largest?) common denominator of two numbers and doesn't actually need or involve pointers at all. It uses two functions and the logic is all correct because it prints out the correct answer to the screen if I do it from the second function, rather than returning it to the main. This is where the problem lies.
When the second function returns the answer value, for some reason it returns what I can only assume is a pointer. I have no idea why it does this. I would be able to work with this and convert it to look up the value - however it seems to be a pointer local the second function and is written over. Nothing on the web that I could find or in my book gave me any idea how to solve the problem.
Thanks if you've read this far. I've rambled far too much.
Here is my code and output. Any help or pointers (excuse the pun) would be greatly appreciated. I know I could just have it print in the second function but I would prefer to know how and why it doesn't return the value like I would like it to.
Code
#include <stdio.h>
int greatestCD (int num1, int num2);
int main(void)
{
int a=0, b=0;
int result;
printf("Please enter two numbers to calculate the greatest common denominator from\n");
scanf("%d%d", &a, &b);
result = greatestCD (a,b);
printf("Using the correct in main way:\nThe greatest common denominator of %d and %d is %d\n",a,b, result);
}
int greatestCD (int num1 ,int num2)
{
if (num2==0){
printf("Using the cheaty in gcd function way:\nThe greatest common denominator is %d\n",num1);
return num1;
} else {
greatestCD(num2,(num1%num2));
}
}
Output (using 12 and 15 - the answer should be 3)
C:\Users\Sam\Documents\C programs>gcd
Please enter two numbers to calculate the greatest common denominator from
12
15
Using the cheaty in gcd function way:
The greatest common denominator is 3
Using the correct in main way:
The greatest common denominator of 12 and 15 is 2293524
Such a simple solution from frankodwyer. It's tiny things like that I either can't spot or don't know about. So what was being returned wasn't a pointer and was just junk?
Thanks a million.