Jeungwoo Park Jeungwoo Park - 2 months ago 8
C Question

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

#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?

Answer

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;
}
Comments