C- Interaction between pointers, arrays, and structs -
i've been reading on pointers , arrays in c in effort learn how implement vla-ish member of struct. (specifically, need array or array-like object length different between instances of struct defined @ compile-time particular struct instance.)
it seems me though this:
typedef struct example{ unsigned char length; char *data; }example; int buildexample(example e, unsigned char l, char * const d){ e.length = l; e.data = d; return 0; //not safe know, fact isn't relevant question. } main(){ example e; unsigend char = 5; char b[] = {1, 2, 3, 4, 5}; buildexample(e, a, b); int = 0; while(i < e.length){ printf("%d %d\n", i, e.b[i]); i++; } printf("%d %d\n", i, e.b[i]); }
should result in output:
0 1 1 2 2 3 3 4 4 5 5 unknown value or segfault, not sure
and various pointers , memory cells , such should go this:
before call buildexample: example e.data b address 0, 1, 2... |null pointer| |ptr address 0| | 1 | 2 | 3 | 4 | 5 | after call buildexample: example e.data address 0, 1, 2... |ptr address 0| | 1 | 2 | 3 | 4 | 5 |
but instead segfault. if swap out e.data b, 'unknown value' outcome (32765, 32766 or 32767, whatever reason), , if swap out e.data new int* c, defined , set equal b in main, same result b, implies me e.data not in fact being set b buildexample.
why not?
when calling buildexample()
you're passing copy of e
struct created in main()
, changes lost when function returns. use pointer instead.
int buildexample(example *e, unsigned char l, char * const d){ e->length = l; e->data = d; return 0; //not safe know, fact isn't relevant question. }
and when calling:
buildexample(&e, a, b);
however have other errors such unsigend char = 5;
(should unsigned
not "unsigend") , trying access element named b
(should data
).
buildexample(&e, a, b); while(i < e.length){ printf("%d %d\n", i, e.data[i]); i++; } printf("%d %d\n", i, e.data[i]);
hope helps!
Comments
Post a Comment