Saturday, 15 August 2015

c - Why is my initialization function returning null? -



c - Why is my initialization function returning null? -

i'm writing programme in c first time. have bit of experience c++, c's reliance on pointers , absence of new , delete throwing me off. defined simple info structure, , wrote function initialize (by taking pointer). here's code:

//in foo.h #include <stdio.h> #include <stdlib.h> typedef struct foo { struct foo * members[25] ; } foo ; void foo_init(foo * f) ; void foo_destroy(foo * f) ; //in foo.c void foo_init(foo * f) { f = (foo*)malloc(sizeof(foo)); (size_t = 0 ; < 25 ; i++) { f->members[i] = null ; } } //define foo_destroy() //in main.c #include "foo.h" int main(int argc, const char * argv[]) { foo * f ; foo_init(f) ; /* why f still null here? */ foo_destroy(f) ; /* ... */ homecoming 0; }

when tested foo_init() function on f (pointer foo struct), null after function returned. pointer f inside foo_init() initialized fine, however, don't think problem init function itself. shot in dark, related way c handles passing value/passing reference (something still don't exclusively have grasp on)? how can right this?

void foo_init(foo* f)

in c parameters passed value. here pass parameter named f, of type foo*. in function assign f. since parameter passed value, assigning local copy, private function.

in order caller see newly allocated struct, need level of indirection:

void foo_init(foo** f) { *f = ...; }

and @ phone call site:

foo* f; foo_init(&f);

now, since function designed send new value caller, , function has void homecoming value, create more sense homecoming new value caller. this:

foo* foo_init(void) { foo* foo = ...; homecoming foo; }

you phone call so:

foo* f = foo_init();

c pointers initialization

No comments:

Post a Comment