can any one tell that i have a variable which is declared
as static but i want this variable to be visible to the
other files? how?
Answers were Sorted based on User's Feedback
Answer / vadivelt
It is not possible to directly access the static variable
of one file from another file. But we can access is it
in different way(by accessing the location).
Lets have a file1.c with following code:
static int a;
int *ptr = &a;/*ptr in Global scope, so by default its
storage class is extern*/
void func(void)
{
a = 30;
}
Here 'a' is static variable and it cannot be directly
accessed from another file. So create a pointer of same
data type (*ptr) and assign the address of the variable to
the pointer. Now whenever the variable value is changed in
file1.c, it will be updated in the location of 'a' and
pointer holds that location.
Now Lets have a second file with name main.c with the foll
code
#include<stdio.h>
#include<conio.h>
main()
{
extern int *ptr;
printf("%d\n", *ptr);
func();
printf("%d", *ptr);
getch();
}
Since *ptr is a extern variable and it holds the address of
a, whenever the value of the variable is changed in
file1.c, it will reflect in main.c also.
Here, when 1st printf() is executed, 'a' value would be 0.
Cos it is a static and defualt initial value is 0.
before 2nd printf() is encountered, 'a' value is changed to
30 in file1.c using func();
since we are accessing address of the variable using ptr
,the same value will reflect in main.c also.
In the same way if u want to change the value of static
variable in main.c
Just use *ptr = somevalue; it will reflect in variable 'a' in
file1.c
Is This Answer Correct ? | 3 Yes | 0 No |
c programming of binary addition of two binary numbers
for example user gives input as " 20 or 20.0 or rs 20.0 or 20.00 or rs20 and so .. on " and the output should be stored as " rs.20.00 " in a variable
find the value of y y = 1.5x+3 for x<=2 y = 2x+5 for x>2
Why c language?
Take an MxN matrice from user and then sum upper diagonal in a variable and lower diagonal in a separate variables. Print the result
write c program to display output 10(10+20)+(10+20+30)+ ... n term
0 Answers Hindustan Gum Chemicals,
What is the difference between new and malloc functions?
write a program for odd numbers?
actually i have 2 years teaching experience as computer faculty but now i am a DBA but when i go for interview many peoples asked me why i left my teaching profession and why i want to come in this field kindly give me the proper answer of this queston
Explain what is the best way to comment out a section of code that contains comments?
write a program to display numbers from 1 to 10 and 10 to 1?
Are pointers integers in c?