Pointers in C and C++
Pointers in C and C++
A pointer is a variable that stores the address of another variable. Unlike other variables that hold values of a certain type, pointer holds the address of a variable. For example, an integer variable holds (or you can say stores)
an integer value, however an integer pointer holds the address of a integer variable.
Pointers store address of variables or a memory location.
Syntax:
datatype *var_name;
Ex: int *ptr;
To access address of a variable to a pointer, we use the unary operator & (ampersand) that returns the address of that variable. For example &x gives us address of variable x.
#include <stdio.h>
int main()
{
int x;
// Prints address of x
printf("%p", &x);
return 0;
}
EX:
#include <stdio.h>
int main()
{
int num = 10;
printf("Value of variable num is: %d", num);
/* To print the address of a variable we use %p
* format specifier and ampersand (&) sign just
* before the variable name like &num.
*/
printf("\nAddress of variable num is: %p", &num);
return 0;
}
Output:
Value of variable num is: 10
Address of variable num is: 0x7fff5694dc58
One more operator is unary * (Asterisk) which is used for two things :
To declare a pointer variable: When a pointer variable is declared in C/C++, there must a * before its name.
C program for pointer variables.
#include <stdio.h>
int main()
{
int x = 10;
int *ptr; //ptr is an integer type pointer variable
ptr = &x; //& used for get address so ptr store the address of x
return 0;
}
To access the value stored in the address we use the unary operator (*) that returns the value of the variable
located at the address specified by its operand.
C program of * for pointers in C
#include <stdio.h>
int main()
{
int y = 5;
int *ptr = &y;
printf("Value of y = %d\n", *ptr);
printf("Address of y = %p\n", ptr);
*ptr = 10;
printf("After doing *ptr = 10, *ptr is %d\n", *ptr);
return 0;
}
Comments
Post a Comment