Reputation: 5242
I have a small code something like this:
#include <stdio.h>
int *ptr1;
int *ptr2;
void some_function(void)
{
int B = 5;
ptr2 = &B;
}
main (){
int C, D;
int A =10;
int *ptr3;
ptr1= &A;
ptr3=ptr2;
some_function();
C = *ptr1 + *ptr2;
printf("Sum of the numbers C= %d\n",C);
some_function();
D = *ptr1 + *ptr3;
printf("Sum of the numbers D= %d\n",D);
}
Why dont I get the result for D but get the result for C? I get the result for the print statement Sum of the numbers C=15
but nothing for the last print statement for D. What is the difference between local and global pointers ( I mean both ptr1 and ptr2 are defined global and ptr3 is define local)? Is the pointer assignment ptr3=ptr2
valid? are there any significant difference with pointer to local variable Vs. pointer to global variable ?
Upvotes: 0
Views: 1062
Reputation: 58291
ptr3=ptr2;
coped before the call of function some_function();
so wrong address assigned to ptr3
that is NULL because ptr2 is 0 (by-default value of global variable).
Do like this:
some_function();
ptr3=ptr2;
D = *ptr1 + *ptr3;
printf("Sum of the numbers D= %d\n",D);
Also, following code running correct because ptr2
value is used after call of some_function();
function.
some_function();
C = *ptr1 + *ptr2;
printf("Sum of the numbers C= %d\n",C)
Ooh!, Scope of variable ptr2
points to local to some_function().
void some_function(void)
{
int B = 5;
ptr2 = &B;
}
Do like this:
void some_function(void)
{
int* B = calloc(1,sizeof(int));
*B = 5;
ptr2 = B;
}
Also don't forget to free(ptr2)
after print statement;
Upvotes: 2
Reputation: 145919
ptr3 = ptr2;
ptr3
is initialized with the value of ptr2
which is NULL
. It is NULL
because you didn't initialize it and it has static storage duration.
then you do
D = *ptr1 + *ptr3;
You are dereferencing ptr3
which is a null pointer: this is undefined behavior. The value of ptr2
may have changed during your program, but ptr3
is still a null pointer.
EDIT: For the sake of completeness (well, sort of):
void some_function(void)
{
int B = 5;
ptr2 = &B;
}
B
object lifetime ends when the functions some_function
exits. You cannot access B
through ptr2
after some_function
has returned. It means:
C = *ptr1 + *ptr2;
also invokes undefined behavior because you are dereferencing ptr2
which is an invalid pointer in this statement.
Upvotes: 7