Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it possible? passing address of local static value to main pointer?

Tags:

c

pointers

static

#include<stdio.h>

void f(int *p) {
    static int data = 5;
    p=&data;
}

int main(void) {
    int *ip=NULL;
    f(ip);
    printf("%d\n", *ip);
    return 0;
}

if it is possible. what is cause error? how can I fix the code?

like image 334
Jeungwoo Park Avatar asked Jan 20 '26 05:01

Jeungwoo Park


2 Answers

In this way you end up changing the value of a local pointer, you need to pass a pointer to pointer (&) from main and use the dereference operator (*) in the function:

#include <stdio.h>

void f(int **p) {
    static int data = 5;

    *p = &data;
}

int main(void) {
    int *ip = NULL;

    f(&ip);
    printf("%d\n", *ip);
    return 0;
}

But usually we prefer to work with the same level of indirection returning the address from the function, this is easier to read (at least for me):

#include <stdio.h>

int *f(void) {
    static int data = 5;

    return &data;
}

int main(void) {
    int *ip = f();

    printf("%d\n", *ip);
    return 0;
}
like image 149
David Ranieri Avatar answered Jan 21 '26 22:01

David Ranieri


You have to pass a pointer to the pointer to change the value of the actual pointer:

void some_fun(int **p)
{ 
    static int i = 10;
    *p = &i;
}

That being said, it is not necessarily advisable to do that. The only direct use I could think of is to delay the execution of the initialization of a global until its first use.

like image 22
midor Avatar answered Jan 21 '26 20:01

midor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!