Pointers in C language is a variable that stores/points the address of another variable. The pointer variable might be belonging to any of the data types such as int, float, char, double, short, etc.
c pointers example
#include <stdio.h> int main() { int i; int*ptr; ptr=&i; i=10; printf("\n%p %p",&i,ptr); //printf("\n%x %x",&i,ptr); printf("\n%d %d",i,*ptr); *ptr=20; //i=20; printf("\n%u %u",&i,ptr); printf("\n%d %d",i,*ptr); return 0; }
Output:
[quote]
address(Hexadecimal format) Address(hexadecimal format)
10 10
Address(Decimal format)Address(Decimal format)
20 20
[/quote]
Analysis
Let’s discuss above program, we created a pointer to integer variable ‘ptr‘ and storing an integer variable i.e &i; `%p` or ‘%x‘ will print hexadecimal format data on screen i.e &i and ptr both should be same and ‘%u’ will print unsigned decimal format address. ‘ptr’ is storing ‘&i’ that’s why ‘i’ and ‘*ptr’ values should be the same.
c pointers exam questions
#include <stdio.h> int main() { int a,b; int*ptr; ptr=&a; a=10; b=20; printf("\n%d %d %d",a,b,*ptr); *ptr=30; ptr=&b; b=40; printf("\n%d %d %d",a,b,*ptr); return 0; }
Output:
[quote]
10 20 10
30 40 40
[/quote]
c pointers example programs
#include <stdio.h> int main() { short a,b; char*ptr; ptr=&a; a=32767; b=*ptr; printf("\n%d %d %d",a,b,*ptr); *ptr=0; printf("\n%d %d %d",a,b,*ptr); return 0; }
Output:
[quote]
[/quote]
Analysis
Let’s discuss above program, we created a pointer to char variable ‘ptr‘ and storing an integer/short variable is this kind of approach suspicious pointer conversion.
In c programming language we can store any kind of variable address into any type of pointers, but we can see the difference at the time of accessing data or modifying data using ‘*’ operator.
In the above program, we are trying to access an integer variable data using ‘char*’ so it will access only one-byte data and if we assign any value using ‘*pt’ then also it will modify 1st-byte data only.
#include <stdio.h> int main() { int a,b; char*ptr; ptr=&a; a=398; b=*ptr; printf("\n%d %d %d",a,b,*ptr); *ptr=255; printf("\n%d %d %d",a,b,*ptr); return 0; }
Output:
[quote]
[/quote]
c programming pointers examples
#include <stdio.h> int main() { int a,b; unsigned char*ptr=(unsigned char*)0; ptr=&a; a=511; b=*ptr; printf("\n%d %d %d",a,b,*ptr); *ptr=10; printf("\n%d %d %d",a,b,*ptr); return 0; }
Output:
[quote]
[/quote]