c - How to find the 'sizeof' (a pointer pointing to an array)? -
first off, here code:
int main() { int days[] = {1,2,3,4,5}; int *ptr = days; printf("%u\n", sizeof(days)); printf("%u\n", sizeof(ptr)); return 0; } is there way find out size of array ptr pointing (instead of giving size, 4 bytes on 32-bit system)?
no, can't. compiler doesn't know pointer pointing to. there tricks, ending array known out-of-band value , counting size until value, that's not using sizeof.
another trick 1 mentioned zan, stash size somewhere. example, if you're dynamically allocating array, allocate block 1 int bigger 1 need, stash size in first int, , return ptr+1 pointer array. when need size, decrement pointer , peek @ stashed value. remember free whole block starting beginning, , not array.
Comments
Post a Comment