How to pass pointer to int when have got int? [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have got a code:
void fun1(int ** i) {
*i = new int(0);
}
void fun2(int *& i) {
i = new int(69);
}
int main()
{
using namespace std;
int a = new int(42);
fun1(&a);
cout << "fun1" << a << endl;
fun2(&a);
cout << "fun2" << a << endl;
}
And I want to pass "a" into functions fun1 and fun2. Can I do it without creating a pointer that will point to a? Can I pass "a" somehow?

One of the functions takes a pointer to a pointer:
void fun1(int ** i)
the other one takes a reference to a pointer:
void fun1(int *& i)
Calling them without having a pointer variable is rather pointless, as those functions main effect (most likely) is to change the adress the passed pointer (passed by reference, either as pointer or reference) is pointing to so that it can be used by the caller.
Lets suppose the following would work
int a;
fun1(&(&a));
The function would change the adress the "temporary" (&a which is a pointer to int) is pointing to, but you would have no means to access it.

1st of all int a = new int(42); is wrong the operator new creates the object on the heap and returns the pointer to the newly created object. you are trying to assign it to an int. at best it should look like int* a = new int; *a = 42; at which time your code is responsible for deleting it.
Now if you have a function like void func(int* pA) {} and have a local variable like int a = 42; and you want to pass it to your function, you would call your function like func(&a);.
2nd both your functions are creating memory leak. you are creating a new pointer that is never deleted.
3rd if you want to change the value of a in your functions, all you need is something like this:
void func1(int* pA)
{
*pA = 42;
}
or you can do something like this:
void func2(int& rA)
{
rA = 42;
}
I think you have not understood the meaning of pointer and references.

To have a reference without pointer, just do foo(int &a) {a = 43} and call the function like this: foo(a)

Operator new returns pointer, so you must write int* a = new int(42);. After you can call the functions as follows:
fun1(&a);
fun2(a);
And also don't forget to delete allocated memory with new:
#include <iostream>
void fun1(int ** i)
{
delete *i;
*i = new int(0);
}
void fun2(int *& i)
{
delete i;
i = new int(69);
}
int main()
{
using namespace std;
int *a = new int(42);
fun1(&a);
cout << "fun1: " << a << endl;
fun2(a);
cout << "fun2: " << a << endl;
delete a;
}

Related

How to keep the address stored in a pointer passed as an argument consistent across all function calls

I can pass any argument by reference and the changes to that variable in any of the function calls are reflected in other function calls too.
Likewise if I want to keep the address stored in a pointer consistent across all the function call such that it behaves like we are passing a pointer by reference.
You can pass pointers by reference too, as suggested in a comment.
#include <iostream>
void f(int * & p) {
std::cout << p << std::endl;
}
int main() {
int x;
int * p = &x;
std::cout << p << std::endl; // This prints the same...
f(p); // ... as this.
}

Why is the pointer declared in main() not changed? [duplicate]

This question already has answers here:
When I change a parameter inside a function, does it change for the caller, too?
(4 answers)
Closed 4 years ago.
I know call by pointers in which we pass address of variables.Something like this:
void swap(int *x, int *y)
{
int temp;
temp = *x; /* save the value at address x */
*x = *y; /* put y into x */
*y = temp; /* put x into y */
return;
}
swap(&a, &b);
And also call by reference,in both of these methods the changes made in the function are reflected in actual arguments' variable.
But why are actual parameters passed in this case of call not changed:
#include <iostream>
using namespace std;
void foo(int* c){
c=c+1;
}
int main()
{
int a=5;
int *c=&a;
cout<<&c<<endl; //0x7ffe1a74f3b0
foo(c);
cout<<*c<<endl;//5
cout<<&c<<endl;//0x7ffe1a74f3b0
}
Here c passed to foo() is address of a.So how this is call by value.
Here c should have printed garbage value according to me.Please explain what has happened here.
And also call by reference, in both of these methods the changes made in the function are reflected in actual arguments' variable.
There is an important difference, though: the changes are always made to whatever is referenced/pointed to, never to the reference/pointer itself (modifying a reference is impossible in general).
That is why assigning c a new value inside foo has no effect on c outside foo: the pointer passed to a function is copied.
If you need to modify the pointer, you need to add another level of dereference by passing a pointer reference or a pointer to a pointer.
Following on from comments, the variable c defined in function main is a different variable to the parameter c of function foo. If you want foo to be able to modify main's c, that is modify the address that c's pointer type holds, then you need to pass either a reference or pointer to c to the function instead.
Here is an example that shows the difference between passing c by value (as int *), or by reference (as int ** or int *&). Don't be fooled by the fact that int * is a pointer type, that means that it can receive an int by reference or an int * by value. And since main's c is int * rather than int, main c is being passed by value.
Note the differences in how the functions are called (whether c needs the address operator & in the function call) and the outcome of each function.
#include <iostream>
using namespace std;
void foo_int_ptr(int* c)
{
c=c+1;
}
void foo_int_ptr_ptr(int** c)
{
*c=*c+1;
}
void foo_int_ptr_ref(int*& c)
{
c=c+1;
}
int main()
{
int a=5;
int *c=&a;
cout << "&c=" << &c << ", c=" << c << ", *c=" << (c==&a ? std::to_string(*c) : std::string("INVALID PTR")) << endl;
foo_int_ptr(c);
cout << "&c=" << &c << ", c=" << c << ", *c=" << (c==&a ? std::to_string(*c) : std::string("INVALID PTR")) << endl;
foo_int_ptr_ptr(&c);
cout << "&c=" << &c << ", c=" << c << ", *c=" << (c==&a ? std::to_string(*c) : std::string("INVALID PTR")) << endl;
foo_int_ptr_ref(c);
cout << "&c=" << &c << ", c=" << c << ", *c=" << (c==&a ? std::to_string(*c) : std::string("INVALID PTR")) << endl;
}
Output:
&c=0x7e02d81808b8, c=0x7e02d81808ac, *c=5
&c=0x7e02d81808b8, c=0x7e02d81808ac, *c=5
&c=0x7e02d81808b8, c=0x7e02d81808b0, *c=INVALID PTR
&c=0x7e02d81808b8, c=0x7e02d81808b4, *c=INVALID PTR
there is a mistake in your thinking about this ..
int *c = &a;
this doesn't mean that c "contains" address of a, this means that c is a pointer TO the address of a. Passing a pointer to foo() will not do anything.

why we can not reference a pointer but values [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
#include <iostream>
using namespace std;
void reference(int &ref){
cout << ref << endl;
}
void pointer(int *ref){
cout << *ref << endl;
}
int main(){
int *i = new int[1];
*i = 10;
reference(*i); // fine
reference(i); // why not compiling!!! why not referencing to my pointer??
pointer(i); // fine
}
I want to reference a pointer, as i can see i am allowed to reference value but not pointer, why??
An object of type int* cannot be automatically converted to int&.
I think you are looking for something like:
void reference(int& ref){
cout << ref << endl;
}
void reference(int*& ref){
cout << *ref << endl;
}
Then, you can use both:
int main(){
int *i = new int[1];
*i = 10;
reference(*i);
reference(i);
return 0;
}
This line
reference(i);
is trying to pass in a int * - not an ``int` variable. Hence will not compile.
See the signature of the function
First of all "crash" is a term you can only use after getting through compiler...
void reference(int &ref)
This function is taking reference to integer as its parameter while you are passing pointer to integer through
reference(i)
Change your function's signature to something like:-
void reference(int* &ref)
for this call to work. OR change call to something like:-
int i;
reference(i);
for this function to work.

Changing target of pointer in function (to a dynamically created object) [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
That may well be silly, but I'm going crazy here ..
Why does pTest doesnt point on the new int after test function in main ? It causes seg fault. And how can I do it.
In my real code I need to pass a pointer and dynamically create the object because pTest is a subclass of a virtual class (reading from file so I don't know in advance)
void test(int* pTest)
{
int *p = new int(2);
pTest = p;
std::cout << "pTest : " << *pTest << std::endl;
return;
}
int main()
{
int *pTest = NULL;
test(pTest);
std::cout << "pTest : " << *pTest << std::endl;
return 0;
}
If you want to mutate value passed as a parameter you have to provide pointer to it. That means if you want to change value of a given int you are passing int* . In your case you want to mutate int* so that you need to pass it as int** instead.
you need to pass pTest by reference: void test(int*& pTest) if you want the pTest value to be altered outside the scope of this function.
void test(int*& pTest)
{
int *p = new int(2);
pTest = p;
std::cout << "pTest : " << *pTest << std::endl;
return;
}

C++: save variable value for next call of the function

Is there a way to initialize a variable in a function and save its value for next call of function?
I'm making application in qt and i have one function connected with a signal. I want an variable in that function to change after the other one reaches its goal. Here is the body of that function:
void objekt::advance(int phase)
{
if(!phase) return;
QPointF location = this->pos();
if (int(location.x())==200 || int(location.x())==-200)
{
smijer=-smijer;
}
setPos(mapToParent(smijer,0));
}
I defined the smijer variable as static int. But i dont'know how to initialize it only once, when program starts, and how to keep its new value after each call of the function.
Your answer is in your question basically. Static variables (either a class member or local variable of a function) is initialized only once where it is terminated. For example;
#include <iostream>
int foo () {
static int sVar = 5;
sVar++;
return sVar;
}
using namespace std;
int main () {
int iter = 0;
do {
cout << "Svar :" foo() << endl;
iter++;
}while (iter < 3);
}
if you write a program like that it will print out Svar values just like;
Svar :6
Svar :7
Svar :8
So as you see although we call foo function three times the initialization of a static varible is done only once.
Why am I being downvoted? He wants to change a variable and preserve the states after function calls. (He doesn't specify whether the variable is a member of the class or anything, so I'm assuming it's not. I'll change my answer if he clarifies and states his question less ambiguously.)
You're going about this wrong. To keep a variable after a function's scope ends, you have to allocate it on the heap rather than the stack. You can use new or malloc to do this, but you also have to free this memory with delete and free, in that order.
With new and delete:
#include <iostream>
void modify(int * p){
(*p)++;
}
int main(void){
int * pointer = new int;
*pointer = 5;
std::cout << *pointer << std::endl;
modify(pointer);
std::cout << *pointer << std::endl;
delete pointer;
return 0;
}
And with malloc and free:
#include <iostream>
#include <cstdlib>
void modify(int * p){
(*p)++;
}
int main(void){
int * pointer = (int*)malloc(sizeof(int)); //DO NOT CAST IN C
*pointer = 5;
std::cout << *pointer << std::endl;
modify(pointer);
std::cout << *pointer << std::endl;
free(pointer);
return 0;
}
new does provide facilities for deleting arrays quickly and is better overall for normal use C++.
If smijer is a member of class objekt, then do it like this:
objekt.h:
class objekt
{
...
static int smijer;
...
};
objekt.cpp
int objekt::smijer = YOUR_INITIALIZATION_VALUE;
On the other hand, if you want/need smijer to be a global variable, then do it like this:
globals.h:
extern int smijer;
globals.cpp //Or another .cpp file
int smijer = YOUR_INITIALIZATION_VALUE;
Although in this case I'd stick it in a namespace. In this case it isn't declared static but it does have the lifetime of your program.
Declare the variable as static inside the function and the valued will be remembered. You don't need to initialize it. But you can if you want to.