« Pointers and functions
Understand pointers and functions
How pointers will behave when passed to functions
1void print(int *p)2{3 cout << *p << endl;4}56void incrementPointer(int *p)7{8 p++;9}1011void increment(int *p)12{13 (*p)++;14}1516int i = 10;17int *p = &i;18print(p);1920cout << "p: " << p << endl;21incrementPointer(p);22cout << "p: " << p << endl;2324cout << "*p: " << (*p) << endl;25increment(p);26cout << "*p: " << (*p) << endl;
Both incrementPointer()
and increment()
are pass by value but we are passing address using pass by value. In increment()
we change the value pointed by address so value will update in main but in incrementPointer()
we are updating the address so changes won't be reflected in main
1// arr is passed as pointer actually2int sum(int arr[], int size)3{4 cout << "sizeof(arr): " << sizeof(arr) << endl;5 return 0;6}78// if arr is passed as pointer actually then lets try pointer910int sum1(int *arr, int size)11{12 cout << "sizeof(arr): " << sizeof(arr) << endl;13 int ans = 0;14 for (int i = 0; i < size; i++)15 {16 ans = ans + arr[i];17 }18 return ans;19}2021int arr[10];22cout << "sizeof(arr): " << sizeof(arr) << endl;23sum(arr, 10);2425cout << "sum: " << sum(arr, 10) << endl;26cout << "sum1: " << sum1(arr + 3, 7) << endl;
arr
is passed as pointer actually when passed to pointer. You can verify this by using sizeof()
operator. sizeof()
will give 8 in functions but will give 40 in main. If arr
is passed as pointer actually then we can use pointers also to pass arrays. Even if arr
is pointer we can write arr[i]
as this will be treated as *(arr+i)
Here as we are using pointers we can pass part of the array arr + 3
Final code
1#include <iostream>2#include <iomanip>3#include <algorithm>4#include <string>5#include <cstring>6#include <vector>7#include <cmath>8#include <map>9#include <climits>10// climits for INT_MIN11#include <unordered_map>12using namespace std;1314void print(int *p)15{16 cout << *p << endl;17}1819void incrementPointer(int *p)20{21 p++;22}2324void increment(int *p)25{26 (*p)++;27}2829int sum(int arr[], int size)30{31 cout << "sizeof(arr): " << sizeof(arr) << endl;32 return 0;33}3435int sum1(int *arr, int size)36{37 cout << "sizeof(arr): " << sizeof(arr) << endl;38 int ans = 0;39 for (int i = 0; i < size; i++)40 {41 ans = ans + arr[i];42 }43 return ans;44}4546int main()47{48 int i = 10;49 int *p = &i;50 print(p);5152 cout << "p: " << p << endl;53 incrementPointer(p);54 cout << "p: " << p << endl;5556 cout << "*p: " << (*p) << endl;57 increment(p);58 cout << "*p: " << (*p) << endl;5960 int arr[10];61 cout << "sizeof(arr): " << sizeof(arr) << endl;62 sum(arr, 10);6364 cout << "sum: " << sum(arr, 10) << endl;65 cout << "sum1: " << sum1(arr + 3, 7) << endl;66 // here we passing part of the array6768 return 0;69}