Pointers
Allows direct manipulation of memory contents
Uses the & operator to refer to the address
e.g:
a = 123
&a = ffbff7dc //they are in hexa
During printf , uses %p as the format specifier for address
A pointer variable is a variable that contains the address of another variable
a_ptr here is a pointer variable and contains the address of variable a
This is like a pointer to the white box
Declaring a pointer
Syntax: type *pointer_name
Assigning a value to a pointer
int a = 123;
int *a_ptr;
a_ptr = &a;
or
-We use the &(Name of variable) to point to the address where the variable is stored.
- We use *(Name of pointer) to refer to a variable
- We use the (Name of pointer) as a pointer to some variable of the same type
However, only *(Name of pointer) can access the value of the pointer variable
Whatever happened to the pointer will affect the original value
In short, a pointer is a clone of the variable with its memory address stored.
After assigning,
*a_ptr will be the same as a
printf("a = %d\n", *a_ptr);
printf("a = %d\n", a);
Will be the same
Purpose of pointers
- To pass the address of two or more variables to a function so that function can pass back to its caller new values for the variables
- To pass the address of the first element of an array to a function so that the function can access the entire array
Pointers and Functions
Functions will get rid of its data after it has been called, however, we can make use of pointers to ensure that the information retains
Declaration of function:
Void my_fun(int * , int *);
Function:
void my_fun(int *pt_1, int *pt_2){
int temp;
temp = *pt_1;
*pt_1 = *pt_2;
*pt_2 = temp;
}
int temp;
temp = *pt_1;
*pt_1 = *pt_2;
*pt_2 = temp;
}
//this fn swaps
When calling the function from the main, we input:
my_fun(&a,&b)
Assuming that a and b are integers
Use *(Nameofpointer) to change the data
Use (Nameofpointer) to change address
Assign the address using &(variable name)
<Prev 2.C Prog Next 3. Arrays and Type struct>