I've been reading up on pointers and arrays in C in an effort to learn how to implement something VLA-ish as a member of a struct. (Specifically, I need an array or array-like object with length different between instances of the struct but defined at compile-time for any particular struct instance.)
It seems to me as though something like 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 I know, but that fact isn't relevant to the question.
}
main(){
example e;
unsigend char a = 5;
char b[] = {1, 2, 3, 4, 5};
buildExample(e, a, b);
int i = 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 something like this output:
0 1
1 2
2 3
3 4
4 5
5 some unknown value or a segfault, not sure which
and the various pointers and memory cells and such should go something like this:
before call to buildExample:
example e.data b address 0, 1, 2...
|null pointer| |ptr to address 0| | 1 | 2 | 3 | 4 | 5 |
after call to buildExample:
example e.data address 0, 1, 2...
|ptr to address 0| | 1 | 2 | 3 | 4 | 5 |
But instead I just get a segfault. If I swap out e.data for b, I get the 'unknown value' outcome (32765, 32766 or 32767, for whatever reason), and if I swap out e.data for a new int* c, defined and set equal to b in main, I get the same result as b, which implies to me that e.data is not in fact being set to b by buildExample.
Why not?