0

Pointer s doesn't get any value. I can't figure out why.
Variable v in exposeStatic() always get desired values.
Please advise.

main.c

#include <stdio.h>
#include <stdlib.h>
#include "myLib.h"

struct node *s = NULL;

int main() 
{
    populateStatic();
    exposeStatic(s);
    printf("myLib myStatic adress: %p\n", s);
    return(0);
}

myLib.h

#ifndef myLib
#define myLib

struct node
{
    int data;
    struct node *next;
};

void exposeStatic(struct node *v);
void populateStatic();

#endif

myLib.c

#include <stdio.h>
#include <stdlib.h>
#include "myLib.h"

static struct node *myStatic = NULL;

void exposeStatic(struct node *v)
{
    v = myStatic;
}

void populateStatic()
{
    struct node *p = (struct node *)malloc(sizeof(struct node));
    p->data = 855; // assume there is some data from populateStatic() arguments
    p->next = NULL; // assume there is some data from populateStatic() arguments
    myStatic = p;
}
Josiah
  • 207
  • 3
  • 13
  • 1
    `v = myStatic;` overwrites the value passed (if the compiler doesn't optimise it away), and is then forgotten about. – Weather Vane Feb 25 '20 at 15:43
  • Does this answer your question? [make the parameter as reference](https://stackoverflow.com/questions/13009684/make-the-parameter-as-reference) – RubberBee Feb 25 '20 at 15:45
  • 1
    Does this answer your question? [Changing address contained by pointer using function](https://stackoverflow.com/questions/13431108/changing-address-contained-by-pointer-using-function) – medalib Feb 25 '20 at 15:46

1 Answers1

3

You're overwriting the local copy of the variable. Instead, pass a pointer to a pointer:

    exposeStatic(&s);

and modify your function accordingly:

void exposeStatic(struct node **v)
{
    *v = myStatic;
}
S.S. Anne
  • 15,171
  • 8
  • 38
  • 76