Global access of static variable

G

gomathy

Can a static variable defined in a module be indirectly accessed in
another module.

File1.c
-------

static int i;
int* ptr;
int main()
{
ptr = &i;
fun();
}

File2.c
--------
extern int* ptr;
fun()
{
printf("value of i = %d",*ptr);

}


Can "i" which is defined in 1.c be accessed in 2.c.

NB:- GCC allows u to do this without any segmentation fault.Can
someone give me the reason.
 
?

=?ISO-8859-1?Q?=22Nils_O=2E_Sel=E5sdal=22?=

gomathy said:
Can a static variable defined in a module be indirectly accessed in
another module.

File1.c
-------

static int i;
int* ptr;
int main()
{
ptr = &i;
fun();
}

File2.c
--------
extern int* ptr;
fun()
{
printf("value of i = %d",*ptr);

}


Can "i" which is defined in 1.c be accessed in 2.c.
'i' cannot be directly accessed, but as you made a (non-static)pointer
to the
same location, you can effectivly manipulate it.
NB:- GCC allows u to do this without any segmentation fault.Can
someone give me the reason.
Cause there is nothing wrong.
 
B

Barry Schwarz

Can a static variable defined in a module be indirectly accessed in
another module.

File1.c
-------

static int i;
int* ptr;
int main()
{
ptr = &i;
fun();
}

File2.c
--------
extern int* ptr;
fun()
{
printf("value of i = %d",*ptr);

}


Can "i" which is defined in 1.c be accessed in 2.c.

Yes. A pointer can be passed between functions and the receiving
function can access the object pointed to as long as that object
remains in existence. This is true whether the "originating" function
calls the receiving function or returns to it.
NB:- GCC allows u to do this without any segmentation fault.Can
someone give me the reason.

While it doesn't apply to this case, there is no guarantee that
invoking undefined behavior will result in a segmentation fault


<<Remove the del for email>>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top