Home »
C programming language
Pointers Declarations in C programming language.
Pointers are the special type of data types which stores memory address (reference) of another variable. Here we will learn how to declare and initialize a pointer variable with the address of another variable?
Pointer Declarations
Pointer declaration is similar to other type of variable except asterisk (*) character before pointer variable name.
Here is the syntax to declare a pointer
data_type *poiter_name;
Let's consider with following example statement
int *ptr;
Here, in this statement
- ptr is the name of pointer variable (name of the memory blocks in which address of another variable is going to be stored).
- The character asterisk (*) tells to the compiler that the identifier ptr should be declare as pointer.
- The data type int tells to the compiler that pointer ptr will store memory address of integer type variable.
Finally, ptr will be declared as integer pointer which will store address of integer type variable.
Pointer ptr is declared, but it not pointing to anything; now pointer should be initialized by the address of another integer variable.
Consider the following statement of pointer initialization
int x;
int *ptr;
ptr=&x;
Here, x is an integer variable and pointer ptr is initiating with the address of x.
Accessing address and value of x using pointer variable ptr
We can get the value of ptr which is the address of x (an integer variable)
- ptr will print the stored value (memory address of x).
- *ptr will print the value which is stored at the containing memory address in the ptr (value of variable x).
Example of Pointers Declarations in C
Here is the simple example to demonstrate pointer declaration, initialization and accessing address, value through pointer variable:
#include <stdio.h>
int main()
{
int x=20; //int variable
int *ptr; //int pointer declaration
ptr=&x; //initializing pointer
printf("Memory address of x: %p\n",ptr);
printf("Value x: %d\n",*ptr);
return 0;
}
Memory address of x: 0x7ffe64f5c814
Value x: 20