I am refreshing my memory of C, and I wanted to test pointers.
I did this simple program, where I call a function that returns a pointer to the largest integer among it's arguments
int*function_pointer (int a, int b, int c);
int main ()
{
printf("Testing pointers\n");// line 1
int*pointer = pointer_function(10,12,36);
//pointer_function(10,102,36) is assigned to int*pointer
printf("Okay, what now...\n");//line 3
return 0;
}
the pointer function
int*function_pointer (int a, int b, int c)
{
int x;
int*ptr = &x;
//initially ptr points to the address of x
if(a > b)
{
if(a > c)
{
printf("a is the greatest\n);
ptr = &a;
}
}
if(b > a)
{
if(b > c)
{
printf("b is the greatest\n");
ptr = &b;
//b is 102, so in this scope ptr points to the address of b
}
}
if(c > a)
{
if(c > b)
{
printf("c is the greatest\n");
ptr = &c;
}
}
return ptr;
//function returns the value of ptr which is the address of b
}
- at main function
function_pointer(10,102,36)
is called - inside
function_pointer(...)
,int a, b, c
are created for that scope - initially
ptr = &x
- since
b = 102
,ptr = &b
- the functions returns the value of ptr
- at main
pointer = ptr
, hencepointer = &b
- but
b
is out of scope, and doesn't have any content - so how come
*pointer = 102
, shouldn't it return a garbage value since b is not withing the scope of the main function