-
May 4th, 2019, 08:04 PM
#1
use pointer
I like to know if some one can show me a way to use pointer in main to argument in function ft?. If it is not possible, I like to know.
Code:
void f(int &v)
{
v = 10;
}
main()
{
//is it possible to pass pointer to function f.
}
-
May 5th, 2019, 03:27 AM
#2
Re: use pointer
Maybe:
Code:
#include<iostream>
using namespace std;
void f(int &v)
{
v = 10;
}
int main()
{
int a = 0;
int *pa = &a;
f(*pa);
cout << a << endl;
}
-
May 5th, 2019, 05:03 AM
#3
Re: use pointer
to use pointer in main to argument in function ft
Sorry, but I'm not sure I understand the question. You can pass a pointer as an argument to f by specifying the parameter as type pointer such as:
Code:
void f(int* pv)
{
*pv = 10;
}
int main()
{
int a = 0;
f(&a);
}
After the call to f, a will have the value 10. This is the 'c' way of doing pass-by-reference,
Is this what you mean...?
All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!
C++23 Compiler: Microsoft VS2022 (17.6.5)
-
May 5th, 2019, 07:12 AM
#4
Re: use pointer
Originally Posted by Y$EA
Code:
void f(int &v)
{
v = 10;
}
main()
{
//is it possible to pass pointer to function f.
}
The simple answer: no, just because the "function f" requires the argument of the type reference to integer.
More complicated answer: it would be possible if one implemented an overloaded function having the argument of type pointer to integer like:
Code:
void f(int *v)
{
*v = 10;
}
And now is my question:
What are you trying to achieve and what for?
Victor Nijegorodov
-
May 5th, 2019, 12:45 PM
#5
Re: use pointer
Originally Posted by Y$EA
I like to know.
Here's a video that explains (some of) the different ways to pass parameters to a function.
https://www.youtube.com/watch?v=TgsH02sORZ0
Note that just because something is possible doesn't mean one should do it. There exists a set of "best usage of C++" recommendations which represents the consensus view on what is best in different situations,
https://github.com/isocpp/CppCoreGui...eGuidelines.md
Last edited by wolle; May 7th, 2019 at 12:19 AM.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|