Todays blog post is on C/C++ pointer. Pointer allows you to access memory address directly.
Pointer points to memory address of a variable.
int n; // A normal variable int *p; // A pointer variable p = &n; // Pointer p holds memory address of n
When we take input in a c/c++ console program,
int number; scanf("%d", &number);
Here actually assigning input to the memory address of number.
& = address of
A integer variable hold 4 bit of space in memory.
So if number's memory address is 466 then next address of another variable will be 470. Because number holds memory address block 466-469.
To be more clear lets assume an array numbers which is an array of integers.
This array can hold 5 integer numbers. And if address of first index is 319 then next will be 323, then 327 and last one is 335.
Lets play with a block of code,
int x, y, z; int *p, *q, *r; p = &x; q = &y; // Assigning address r = &z; x = 10; y = 20; z = 30; p = q; *q = 25; // Assigning value x = 40
In above code x, y, z is normal variable holding value 10, 20, 30. And pointer variable p, q, r point to x, y, z so they have value of x, y, z;
In last 3 lines we have assigned q to p, so p and q both points to y. Next line changing value of q so it will change value of y and p (as p and q now points to same memory address). Lastly changing value of x and it won't affect value of p as p isn't pointing to x anymore.
Subscribe to Sakib Sami' Blog
Get the latest posts delivered right to your inbox