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 |
program to find the magic square
i am using gsm modem ! I USE CMGL COMMAND TO DISPLAY THE LIST OF MESSAGES ! I WANT TO READ EACH MESSAGE ONE BY ONE AND GET EACH MESSAGE INDEX USING C PROGRAM ! THE RESPONSE OF THE MODULE AFTER AT+CMGL IS ---CMGL: 1,"REC READ","+85291234567",,"07/05/01,08:00:15+32",145,37 It is easy to list SMS text messages.---- I WANT THE PROGRAM TO GET THE NUMBER "37"{MESSAGE LENGTH} AS WELL AS "1"(MESSAGE INDEX NUMBER" PLEASE HELP
How can I insert or delete a line (or record) in the middle of a file?
hi how to convert program from notepad to turboc editor can u please help me
main() { char *p; p="Hello"; printf("%c\n",*&*p); }
Write a routine that prints out a 2-D array in spiral order!
What is the acronym for ansi?
Why do we use stdio h and conio h?
how to write a c program to print list of fruits in alpabetical order?
why programs in c are running with out #include<stdio.h>? some warnings are display in terminal but we execute the program we get answer why? eg: main() { printf("hello world "); }
Write a c code segment using a for loop that calculates and prints the sum of the even integers from 2 to 30, inclusive?
Explain how can type-insensitive macros be created?