c - How to allocate memory dynamically when array is declared with 1 element -
consider construction following:
typedef struct { int arrcount; int arr[1]; } samplestruct, *psamplestruct;
i know arr
int array needs dynamic memory allocation @ runtime , arrcount
needs hold count of element. when seek allocate memory of, allow say, 10 elements using malloc, compiler throws error arr must modifiable value
. cant create how allocate memory such array. also, have seen such examples in lot of windows headers, when trying implement it, totally lost.
while arr[1]
not pointer, psamplestruct
is. you'd this:
psamplestruct ss10arr = malloc(sizeof (*ss10arr) + (sizeof(ss10arr->arr) * 9))
create arr[0]
through arr[9]
valid.
note works because arr
@ end of structure.
also note compiler options (like -d_fortify_source
glibc , gcc) complain if seek access subsequent elements because observe overrun.
c windows visual-c++ dynamic-memory-allocation
No comments:
Post a Comment