c - Using function returning pointer as lvalue -
say want dynamically allocate array can hold data, i.e. using void**
type, in c. then, rather re-writing pointer arithmetic logic each time, want simple function returns address of element. why cannot use function in assignment (i.e., can set, element's value)?
here's example code:
#include <stdio.h> #include <stdlib.h> void printintarray(void** array, size_t length) { printf("array @ %p\n", array); while (length--) { printf(" [%zu] @ %p -> %p", length, array + length, *(array + length)); if (*(array + length)) { printf(" -> %d", *(int*)*(array + length)); } printf("\n"); } } void* getelement(void** array, size_t index) { return *(array + index); } int main(int argc, char** argv) { const size_t n = 5; size_t i; /* n element array */ void** test = malloc(sizeof(void*) * n); = n; while (i--) { *(test + i) = null; } /* set element [1] */ int testdata = 123; printf("testdata @ %p -> %d\n", &testdata, testdata); *(test + 1) = (void*)&testdata; printintarray(test, n); /* prints 123, expected */ printf("array[1] = %d\n", *(int*)getelement(test, 1)); /* new in [2] */ /* fixme lvalue required left operand of assignment */ int testthing = 456; getelement(test, 2) = (void*)&testthing; printintarray(test, n); return 0; }
it wouldn't fist time question has been asked, answer along lines of "you trying assign function, rather return value of function, not allowed". fair enough, can 1 around this? i'm confused!!
implement getelement()
this:
void ** getelement(void ** ppv, size_t index) { return ppv + index; }
and use this:
*getelement(test, 2) = &testthing;
if you'd use macro go way intended:
#define get_element(ppv, index) \ (*(ppv + index))
use this:
get_element(test, 2) = &testthing;
Comments
Post a Comment