Reputation: 13
I am looking for a way to pass a pointer from not main function to another function. A variable x with value 5 sends as pointer to func1, func1 changes variable value to 10, then func1 sends same variable to func2.
I want it to look something like that:
#include <stdio.h>
void func1(int *px);
void func2();
int main(void)
{
int x=5;
printf("x in main %d\n", x);
func1(&x);
return 0;
}
void func1(int *px)
{
*px = 10;
printf("x i funk 1 %d\n", *px);
funk2(); // send to this function a pointer to x, which in this function(func1) is pointed by *px
funk3();
}
void func2()
{
//*px=15 // here I want to change value of x
}
Upvotes: 1
Views: 3461
Reputation: 4788
Simply pass the argument in func1()
to func2()
, as a pointer, px
in func1()
and py
in func2()
will point to the same memory location, the address of x
.
int main(void)
{
int x = 5;
printf("x in main %d\n", x);
func1(&x);
printf("x now %d\n", x);
return 0;
}
void func2(int *py)
{
*py = 15; // here I want to change value of x
}
void func1(int *px)
{
*px = 10;
printf("x in funk 1 %d\n", *px);
func2(px); // send to this function a pointer to x, which in this function(func1) is pointed by *px
}
output:
x in main 5
x in funk 1 10
x now 15
Upvotes: 1
Reputation: 13580
I am completely lost in how to do that.
Using the exact same logic you used for passing the pointer to x
from main
to func1
.
In this case func2
should also accept a pointer to int
and func1
should pass the pointer to func2
that it got from main
:
#include <stdio.h>
void func1(int *px);
void func2(int *px);
int main(void)
{
int x=5;
printf("x in main %d\n", x);
func1(&x);
// x will be 15 here
return 0;
}
void func1(int *px)
{
*px = 10;
printf("x i funk 1 %d\n", *px);
funk2(px); // send to this function a pointer to x, which in this function(func1) is pointed by *px
//funk3(); // this function was not defined anywhere
}
void func2(int *px)
{
*px=15;
}
Upvotes: 1