Original Post
I'm rather stuck at the following and a quick search reveals no solution: I have a pointer to a (typedef) structure. I want to initialize this (foo) and use it in another function (e.g. main). So basically, passing through. However, when a function call returns, the value remains unchanged? Why? I mean, in my understanding, I declare a pointer to a value_t structure and initialize with NULL. Then I invoke bar with the value_t structure passed by reference. Next, foo is invoked with again the value_t structure passed by ref. Foo initializes the structure by allocating memory and setting some values. On return in bar, I want to change some value of value_t, but an assertion is fired. Debugging shows that the value_t is still NULL. Why?
#include <stdio.h>
#include <malloc.h>
#include <assert.h>
typedef struct _val
{
int a;
int b;
} value_t;
int foo(value_t *val)
{
val = (value_t*)malloc(sizeof(value_t));
val->a = 0x65;
val->b = 0x66;
assert(val != NULL);
return 0;
}
int bar(value_t *val)
{
if (val == NULL)
foo(val);
assert(val != NULL);
val->b++;
return 0;
}
int main()
{
value_t *val = NULL;
bar(val);
assert(val != NULL);
free(val);
return 0;
}