Click here to Skip to main content
15,917,176 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
lets say we have a function

C
int func(int* p)
{
....
}


if i want to pass variable k=15 i do:

C
x= func(&k); //and all works fine


what if if i want to pass just 15?(for the code to be more readable is some cases)

C
x=func(15);
x=func((int*)15);
x=func(&15);


these doesnt work or function returns wrong result? is it possible?

What I have tried:

x=func(15);
x=func((int*)15);
x=func(&15);
Posted
Updated 14-Sep-22 4:56am
v2

To pass a pointer (the address of something), you need the "something" to exist in an identifiable memory location.
the simplest way is
C++
const k = 15;
x = func(&k);

For readability, you can adopt a naming convention for constants, suck as calling it k15.
 
Share this answer
 
Comments
CPallini 3-Jan-18 2:33am    
5.
<pre>
#include<iostream>
using namespace std;

void add(const int a)
{
    int y = 10 + a;
    cout<<"value of y : "<<y<<endl;
    //a = a + 4; can't modify
}

void display(const int& p)
{
    //p = p + 3; can't modify the value as using const
    cout<<"value of x : "<<p<<endl;
}

void display2(int const *p)
{
    cout<<"value of p means address of y : "<<p<<endl;
}

int main()
{
    int x = 10;
    add(x);//call by value

    int y =3;
    display(y);//call by reference

    display2(&y);//call by pointer
    cout<<"address of y is : "<<&y<<endl;

    return 0;
}
 
Share this answer
 
Comments
CHill60 14-Sep-22 4:14am    
Reason for my downvote. A code dump without commentary is not a good answer and you have added nothing new to this thread.
jeron1 14-Sep-22 9:59am    
In addition to what CHill60 stated, the OP is tagged as 'C' not 'C++'.
merano99 14-Sep-22 11:06am    
Besides: A question that has been here since 2018 should hardly interest the questioner.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900