Difference between revisions of "Interview Preparation topic : Pointers in C"
Proj user14 (talk | contribs) |
Proj user14 (talk | contribs) |
||
Line 34: | Line 34: | ||
printf("Address of temp variable: %x\n", &temp); /* print the address of variable temp */ | printf("Address of temp variable: %x\n", &temp); /* print the address of variable temp */ | ||
printf("Address stored in ptr variable: %x\n",ptr ); /* prints the address stored in variable ptr */ | printf("Address stored in ptr variable: %x\n",ptr ); /* prints the address stored in variable ptr */ | ||
− | printf("Value of *ptr variable: %d\n", *ptr ); | + | printf("Value of *ptr variable: %d\n", *ptr ); /* prints the value stored at address ptr, this is also known as dereferencing of a pointer */ |
return 0; | return 0; | ||
} | } | ||
Line 42: | Line 42: | ||
Address stored in ptr variable: a54fae34<br> | Address stored in ptr variable: a54fae34<br> | ||
Value of *ptr variable:100 | Value of *ptr variable:100 | ||
+ | |||
+ | |||
+ | <b>Interview Questions on pointers : </b> | ||
+ | |||
+ | 1) What is a NULL Pointer?<br> | ||
+ | ->A pointer pointing to nothing is called as a NULL Pointer Eg: int *x=NULL;<br> | ||
+ | |||
+ | 2) |
Revision as of 23:13, 10 December 2016
What is a Pointer?
A pointer is a variable which contains the address in memory of another variable. Every variable is a memory location and every memory location has its address defined which can be accessed using ampersand (&) operator, which denotes an address in memory.
Lets Look at the following example:
- include <stdio.h>
int main ()
{ int temp; int temp1; printf("Address of temp variable: %x\n", &temp ); printf("Address of temp1 variable: %x\n", &temp1 ); return 0;
}
When the following code is compiled and executed:
Address of temp variable: edf53400
Address of temp1 variable: adf9a5f6
To declare a pointer to a variable do:
type *pointer;
Where type can be int, double, float, char and pointer can be any variable.
Consider the following example:
- include <stdio.h>
int main () {
int temp= 100; /* Stores the value 20 in variable temp */ int *ptr; /* Declares a pointer variable of type int */ ip = &temp; /*store address of temp in pointer variable, so now the address of temp will be in ptr */ printf("Address of temp variable: %x\n", &temp); /* print the address of variable temp */ printf("Address stored in ptr variable: %x\n",ptr ); /* prints the address stored in variable ptr */ printf("Value of *ptr variable: %d\n", *ptr ); /* prints the value stored at address ptr, this is also known as dereferencing of a pointer */ return 0;
}
When we compile and execute the following code:
Address of temp variable: a54fae34
Address stored in ptr variable: a54fae34
Value of *ptr variable:100
Interview Questions on pointers :
1) What is a NULL Pointer?
->A pointer pointing to nothing is called as a NULL Pointer Eg: int *x=NULL;
2)