C. Passing pointers to be modified causing segmentation faults
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("%sn",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]
binary is array of pointers. So each element in it is a pointer.
The segmentation fault is because you are not initializing your array and trying to use it.
You are dereferencing a pointer which is not pointing to any valid memory location.
You need to allocate memory to the members of the array before using them
incorporating all the comments, incorporating error checking, etc. the posted code becomes :
#include <stdio.h>
#include <stdlib.h> // exit(), EXIT_FAILURE
#include <string.h> // memset()
// prototypes
void DecToBin(unsigned int, char *binary);
int main()
{
unsigned int dec;
char binary[sizeof(int)*8 +1];
while(1)
{
if( 1 != scanf("%u", &dec) )
{ // then scanf failed
perror( "scanf for decimal value failed" );
exit( EXIT_FAILURE );
}
// implied else, scanf successful
DecToBin(dec, binary);
printf("In binary is ");
printf("%sn",binary);
}
}
void DecToBin(unsigned int dec, char *binary)
{
size_t counter= sizeof(int)*8;
memset( binary, ' ', counter );
binary[ counter ] = ' '; // terminate string
counter--;
// do...while allows for dec being 0
do
{
binary[counter]= (char)((dec%2)+ 0x30);
dec /= 2;
counter--;
} while(dec);
}
which still has the shortcoming that the user is left with a blank screen and a blinking cursor. IE the code should be prompting the user, by requesting the input value.
链接地址: http://www.djcxy.com/p/72154.html下一篇: C.传递要修改的指针导致段错误