I am making a decimal to binary converter in C for a class. I want to pass a char array to my function as well as the the decimal as an int. ie void DtoB(int decimal, char *array); DtoB will do the math and modify array to be the binary value. Ideally by giving it int values. Main() will just scanf(decimal), DtoB(decimal,array), and printf(array).
Here is what I have. This just returns a segmentation fault
1 #include <stdio.h>
2 #include <math.h>
3
4 void DecToBin(unsigned int, char *binary);
5
6 int main()
7 {
8 unsigned int dec;
9 char *binary[];
10 while(1) {
11 scanf("%d", &dec);
12 DecToBin(dec,*binary);
13 printf("In binary is ");
14 printf("%s\n",binary);
15 }
16 }
17 void DecToBin(unsigned int dec, char *binary)
18 {
19 int counter=0;
20 while(dec) {
21 binary[counter]=dec%2;
22 dec/=2;
23 counter++;
24 }
25 }
I want it done like this since this seems like the best way to be able to do 32 bit integers, while keeping the array at the minimum size. Sorry if I killed formatting. Any help is appreciated.
char *binary[33];
declares an array-of-pointers -- none of which are allocated.DecToBin(dec,*binary)
is the same asDecToBin(dec, binary[0])
. – David C. Rankinchar *binary[];
won't compile; you can't define an array in the body of a function without a non-zero size (GCC may permit a zero size, but that's a compiler extension). You actually wantchar binary[33];
and then passbinary
(not*binary)
to your function. – Jonathan LefflerDecToBin(dec,*binary);
is dereferencing the array/pointerbinary[]
Suggest:DecToBin(dec,binary);
. This is because in C, an array name (in most instances) degrades to the address of the first byte of the array. – user3629249scanf()
to assure the operation was successful. In this case, the returned value should be 1. – user3629249