passing pointer to static struct object

3.1k Views Asked by At

I am trying to modify a static struct object by passing its pointer to another function and modifying it by pointer inside that. But even after execution of modifying function, the values of the struct are intact.

void some_functon_a(....)
{
    static struct some_struct obj;
    modifier_function_b(&obj);
    // obj is not modified as expected in fact not at all
}

void modifier_function_b(struct some_struct *ptr)
{
    // modifying the struct using ptr 
}

Also when I run gdb on this code, I see as soon as code flow enters modifier_function_b() function gdb reports two entries for variable ptr: ptr and ptr@entry. All the modifications are being done on ptr, while ptr@entry which points to real location of obj is not modified. Can somebody point out what may be happening here? Are pointer to static variables kind of const pointers and we can't modify them outside their scope?

One more thing... this behavior is not seen if i remove static qualifier, which led me to think that pointer to static is kind of const pointer.

Thanks in advance :)

1

There are 1 best solutions below

2
On

This program works as expected. It prints out 1 2 then 5 6. Also, you didn't specify language, but this does the expected in both C and C++

#include <stdio.h>

struct bar {
    int i;
    int j;
};

void b(struct bar * foo) {
    foo->i = 5;
    foo->j = 6;
}

void aa(){
    static struct bar a;
    a.i = 1;
    a.j=2;
    printf("%d %d\n", a.i, a.j);
    b(&a);
    printf("%d %d\n", a.i, a.j);
}


int main(){
    aa();

}