I have the following simple code to return a binary number in a array format given an interger and the number of the bits for specifying the interger as binary number.
#include <stdio.h> #include <stdlib.h>
int main ()
{
// int* get_binary_number(int* bit_array, int num, int bit_count);
int* bitcount ( int n, int bit_count) ;
int* bit_array;
int i;
// bit_array = get_binary_number(bit_array, 23, 6);
bit_array = bitcount(23, 6);
printf("\nUsage: \n");
printf("\n the number '23' in binary is ");
for (i=0; i<6; i++)
{
printf("%d", bit_array[i]);
}
return 0;
}
int* bitcount ( int n, int bit_count)
{
int count[bit_count];
int bit_place = bit_count - 1;
while (n)
{
count[bit_place] = n && 1 ;
n >>= 1 ;
bit_place--;
}
return count ;
}
this program does compile with a warning
gcc -c -Wall -c -o test.o test.c
test.c: In function �bitcount':
test.c:36: warning: function returns address of local variable
gcc test.o -o test
But when I try to run it, there is no result.
Any help to fix this is greatly appreciated.
(a) return a pointer to array elements, hence has to abide by the memory allocation rules, eg not being on the stack of the function that just returned.
(b) define a struct that contains the array, then return the struct.
I changed my program to this #include <stdio.h> #include <stdlib.h>
int main ()
{
// int* get_binary_number(int* bit_array, int num, int bit_count);
int* bitcount ( int* count, int n, int bit_count) ;
int* bit_array;
int i;
int temp_array[6];
// bit_array = get_binary_number(bit_array, 23, 6);
bit_array = bitcount(temp_array,23, 6);
printf("\nUsage: \n");
printf("\n the number '23' in binary is ");
for (i=0; i<6; i++)
{
printf("%d", bit_array[i]);
}
return 0;
}
int* bitcount ( int* count, int n, int bit_count)
{
//int count[bit_count];
int bit_place = bit_count - 1;
while (n)
{
count[bit_place] = n && 1 ;
n >>= 1 ;
bit_place--;
\}
return count ;
}
and don't get any warnings/error during compilation,
63 memgen > make
gcc -c -Wall -Werror -c -o test.o test.c
gcc test.o -o test
64 memgen >
64 memgen > test
65 memgen >
but there is no output on the screen as well.
What could be wrong?
#include <stdio.h>
#include <stdlib.h>
int* bitcount ( int * count, int n, int bit_count)
{
/* int count[bit_count]; */
int bit_place = bit_count - 1;
while (bit_count--)
{
count[bit_place] = (n & 1) ;
n >>= 1 ;
bit_place--;
}
return count ;
}
int main (int argc, char **argv)
{
/* int* get_binary_number(int* bit_array, int num, int bit_count); */
int* bitcount ( int* count, int n, int bit_count) ;
int* bit_array;
int i;
int temp_array[6];
/* bit_array = get_binary_number(bit_array, 23, 6); */
bit_array = bitcount(temp_array,23, 6);
printf("\nUsage: \n");
printf("\n the number '23' in binary is ");
for (i=0; i<6; i++)
{
printf("%d", bit_array);
}
printf("\n");
return 0;
}