arrays - C - Pointer points to random values -
i'm pretty confused pointers in general , have no idea why happening. pointer array print out values of array have no idea why happening. explain why or suggest happening?
char *showbits(int dec, char *buf) { char array[33]; buf=array; unsigned int mask=1u<<31; int count=0; while (mask>0) { if ((dec & mask) == 0) { array[count]='0'; } else { array[count]='1'; } count++; mask=mask>>1; } return buf; }
expecting return binary representation of dec, printing produces random garbage.
the problem you're returning reference local array. instead, let caller allocate buffer. i've fixed other problems in code:
#define max_buffer_length (sizeof(unsigned int) * char_bit + 1) char *to_bit_string(unsigned int n, char *buf) { unsigned int mask = uint_max - (uint_max >> 1); char *tmp; (tmp = buf; mask; mask >>= 1, tmp++) { *tmp = n & mask ? '1': '0'; } *tmp = 0; return buf; }
first of all, use unsigned int instead of signed int here, because signed ints converted unsigned ints when used in conjunction unsigned int. second, unsigned ints can have varying number of bits; use sizeof(unsigned int) * char_bit + 1
absolute maximum of number of bits. third, use uint_max - (uint_max >> 1)
handy way value has most-significant bit set, no matter how many value bits number has. fourth: instead of indices, use moving pointer. fifth - remember null-terminate string.
usage:
char the_bits[max_buffer_length]; puts(to_bit_string(0xdeadbeef, the_bits));
output
11011110101011011011111011101111
Comments
Post a Comment