1

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 
}
3
  • And what is your problem with this task? Commented Mar 14, 2018 at 2:33
  • I am completely lost in how to do that. Commented Mar 14, 2018 at 2:35
  • Thank you all, that was easier than I thought. Commented Mar 14, 2018 at 2:48

2 Answers 2

1

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 intand 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;
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.