« 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}
5
6void incrementPointer(int *p)
7{
8 p++;
9}
10
11void increment(int *p)
12{
13 (*p)++;
14}
15
16int i = 10;
17int *p = &i;
18print(p);
19
20cout << "p: " << p << endl;
21incrementPointer(p);
22cout << "p: " << p << endl;
23
24cout << "*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

pointers_to_functions.jpg

1// arr is passed as pointer actually
2int sum(int arr[], int size)
3{
4 cout << "sizeof(arr): " << sizeof(arr) << endl;
5 return 0;
6}
7
8// if arr is passed as pointer actually then lets try pointer
9
10int 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}
20
21int arr[10];
22cout << "sizeof(arr): " << sizeof(arr) << endl;
23sum(arr, 10);
24
25cout << "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_MIN
11#include <unordered_map>
12using namespace std;
13
14void print(int *p)
15{
16 cout << *p << endl;
17}
18
19void incrementPointer(int *p)
20{
21 p++;
22}
23
24void increment(int *p)
25{
26 (*p)++;
27}
28
29int sum(int arr[], int size)
30{
31 cout << "sizeof(arr): " << sizeof(arr) << endl;
32 return 0;
33}
34
35int 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}
45
46int main()
47{
48 int i = 10;
49 int *p = &i;
50 print(p);
51
52 cout << "p: " << p << endl;
53 incrementPointer(p);
54 cout << "p: " << p << endl;
55
56 cout << "*p: " << (*p) << endl;
57 increment(p);
58 cout << "*p: " << (*p) << endl;
59
60 int arr[10];
61 cout << "sizeof(arr): " << sizeof(arr) << endl;
62 sum(arr, 10);
63
64 cout << "sum: " << sum(arr, 10) << endl;
65 cout << "sum1: " << sum1(arr + 3, 7) << endl;
66 // here we passing part of the array
67
68 return 0;
69}