+ 1

It was my whole life question.

#include <iostream> using namespace std; void foo(int *ptr, int *secPtr){ int *sum = new int; *sum = *ptr + *secPtr; cout << *sum; } int main(){ int *a = new int; *a = 5; int *b = new int; *b = 6; foo(*a, *b); return 0; }

14th Aug 2018, 9:47 AM
Oleg Storm
Oleg Storm - avatar
7 Answers
+ 6
foo(&a, &b); doesn't work as it creates arguments of type: int **ptr pointer to pointer of integer so you would get a type mismatch.
14th Aug 2018, 11:39 AM
John Wells
John Wells - avatar
+ 5
Your foo function is looking for two pointers to integers (int *ptr, int *secPtr). Both a and b are declared as pointers to integers with: int *a = new int; int *b = new int; Therefore, they are the correct type to be passed into foo so this works: foo(a, b); You could also declare these: int c,d; and pass them as: foo(&c, &d); making pointers by using the address operator.
14th Aug 2018, 11:34 AM
John Wells
John Wells - avatar
14th Aug 2018, 10:19 AM
Meet Mehta
Meet Mehta - avatar
+ 2
I think i understood: In this line: foo(*a, *b), the value of a and b are exactly variables(5, 6) and you can't pass them to pointers as pointers only accept an adress of variables, thus you can't pass them by reference all the time.
14th Aug 2018, 10:28 AM
Oleg Storm
Oleg Storm - avatar
+ 1
The problem is in int main function, foo can't be called, why? compiler says: no matching function to call for foo();
14th Aug 2018, 9:48 AM
Oleg Storm
Oleg Storm - avatar
+ 1
Meet Mehta, nope
14th Aug 2018, 10:08 AM
Oleg Storm
Oleg Storm - avatar
+ 1
Meet Mehta, this works: (a, b), but i can't quite understand whyđŸ€”
14th Aug 2018, 10:13 AM
Oleg Storm
Oleg Storm - avatar