+ 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; }
7 Antworten
+ 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.
+ 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.
+ 4
+ 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.
+ 1
The problem is in int main function, foo can't be called, why?
compiler says: no matching function to call for foo();
+ 1
Meet Mehta, nope
+ 1
Meet Mehta, this works: (a, b), but i can't quite understand why🤔