Pointers in C
This is another very important concept while Learning C Programming. Every variable is assigning memory location whose address can be retrieved using the address operator &. The address of a memory location is called a pointer.
Pointers and the Address Operator
#include <stdio.h>
int main()
{
int x=10; //integer variable
int *ptrX; //integer pointer declaration
ptrX=&x; //pointer initialization with the address of x
printf("Value of x: %d\n",*ptrX);
return 0;
}
Output
Value of x: 10
Further visit: Basic Concept of Arrays in C language In Just 5 Minutes
What is the pointer variable in C?
A pointer variable is a variable that holds s addresses of memory locations. It can be declared as below:
int *x;
Sample program to work with pointer variables
#include <stdio.h>
int main()
{
int* pc, c;
c = 22;
printf("Address of c: %p\n", &c);
printf("Value of c: %d\n\n", c); // 22
pc = &c;
printf("Address of pointer pc: %p\n", pc);
printf("Content of pointer pc: %d\n\n", *pc); // 22
c = 11;
printf("Address of pointer pc: %p\n", pc);
printf("Content of pointer pc: %d\n\n", *pc); // 11
*pc = 2;
printf("Address of c: %p\n", &c);
printf("Value of c: %d\n\n", c); // 2
return 0;
}
Output on screen:
Address of c: 2686784
Value of c: 22
Address of pointer pc: 2686784
Content of pointer pc: 22
Address of pointer pc: 2686784
Content of pointer pc: 11
Address of c: 2686784
Value of c: 2
Array vs Pointers in C
Pointers and arrays are strongly related. In fact, pointers and arrays are interchangeable in many cases. For example, a pointer that points to the beginning of an array can access that array by using either pointer arithmetic or array-style indexing. Consider the following program.
Example Array vs Pointers in C
#include <stdio.h>
const int MAX = 3;
int main () {
int var[] = {10, 100, 200};
int i, *ptr[MAX];
for ( i = 0; i < MAX; i++) {
ptr[i] = &var[i]; /* assign the address of integer. */
}
for ( i = 0; i < MAX; i++) {
printf("Value of var[%d] = %d\n", i, *ptr[i] );
}
return 0;
}
Output on screen:
Value of var[0] = 10
Value of var[1] = 100
Value of var[2] = 200
Address of var[2] = 0xbfa088b8
Value of var[2] = 200