Thursday, July 9, 2009

What is a pointer used in C Program?

pointer is a variable that holds another variables memory adress. an it can be use like variable.

What is a pointer used in C Program?
The only way to tell a machine to execute instructions is using data and instructions.





The data is passed to proper addresses (typically) in CPU memory and then the instruction is passed to work/execute on data. And there are control registers that branch a program execution. This is where the addresses are very important. This contains the address of next instruction to be executed. Of course the addresses in main memory are also used for individual instructions, cz cpu cannot assume that if u say add then it can take 2 data integers randomly from any where or in the worst case sequentially. This forms the basis for modern computing/processors. This in itself is a complete set of things for you to program a software for any computer. Modern computers how ever include support for hardware and also piped execution. In that case you might have to program for piped sequences of segments of code.





So basically when we are programmin in a language we are skipping all these steps. We write human understandable language like C/Pascal/COBOL... and then the computer generates required assembly code. This might have been simple ( not really as the compilers have to deal with more things even with this simple execution of a single program, where the memory address of loading program is predefined ), but modern computers support multiple parallel programs to execute at same time where the memory address of loading of program is uncertain and not predefined.





So a pointer in C is a way you can reference other variables in C. Whether they be Integers or Floats or Structures. All Pointers occupy same memory of 4 bytes. Its a kind of real address, when compared with your program and not in the sense of the whole address space given to you by memory ( RAM ).





So basically a pointer is a reference to other variables.





Examples:





int a;


int *ptr;





ptr = %26amp;a /*here the ptr contains the real address of a, which means that it can change the value of a*/





For structures you use same way but accessing internal variables is a bit different.





struct Emp


{


int num;


chat name[100];


};





struct Emp a = {1,"Albert Einstein"};


struct Emp *ptr;


ptr = %26amp;a;





/*now to access the values of a with pointer you must do this*/





ptr-%26gt;num = -1111;


strcpy(ptr-%26gt;name,"John Nash"};
Reply:Pointer basically points(refers) to the address to the variables. Can be used to access those variables in function.


No comments:

Post a Comment