Address in C
Before you get into the concept of pointers, let's first get familiar with address in C.If you have a variable var in your program,
&var
will give you its address in the memory, where &
is commonly called the reference operator.You must have seen this notation while using
scanf()
function. It was used in the function to store the user inputted value in the address of var.scanf("%d", &var);
#include <stdio.h>
int main()
{
int var = 5;
printf("Value: %d\n", var);
printf("Address: %u", &var); //Notice, the ampersand(&) before var.
return 0;
}
Output
Value: 5
Address: 2686778
How to create a pointer variable?data_type* pointer_variable_name; int* p;
How Pointer Works?
#include <stdio.h>
int main()
{
int* pc, c;
c = 22;
printf("Address of c: %u\n", &c);
printf("Value of c: %d\n\n", c);
pc = &c;
printf("Address of pointer pc: %u\n", pc);
printf("Content of pointer pc: %d\n\n", *pc);
c = 11;
printf("Address of pointer pc: %u\n", pc);
printf("Content of pointer pc: %d\n\n", *pc);
*pc = 2;
printf("Address of c: %u\n", &c);
printf("Value of c: %d\n\n", c);
return 0;
}
Explanation of the programint* pc, c;
Here, a pointer pc and a normal variable c, both of typeint
, is created.
Since pc and c are not initialized at first, pointer pc points to either no address or a random address. And, variable c has an address but contains a random garbage value.
c = 22;
This assigns 22 to the variable c, i.e., 22 is stored in the memory location of variable c.
Note that, when printing&c
(address of c), we use%u
rather than%d
since address is usually expressed as an unsigned integer (always positive).
pc = &c;
This assigns the address of variable c to the pointer pc.
You see the value of pc is same as the address of c and the content of pc is 22 as well.
c = 11;
This assigns 11 to variable c.
Since, pointer pc points to the same address as c, value pointed by pointer pc is 11 as well.
*pc = 2;
This change the value at the memory location pointed by pointer pc to 2.
Since the address of the pointer pc is same as the address of c, value of c is also changed to 2.
No comments:
Post a Comment
Note: only a member of this blog may post a comment.