c - Binary conversion code Segmentation fault -
i new programing in c (only 2 weeks it). unable figure out why code throwing segmentation fault. able program work if set long int num equal static number. need program able accept user input command line (not once program running)
example: ./binary 7
should output binary number 7 is: 111
i have tried using strcpy(num, argv[0]) throws errors when compiling.
#include<stdio.h> #include <string.h> #include<math.h> void dectobinary(long int num) // function definition { long int remainder[50]; int i=0; int length=0; printf("the binary number %d is: ",num); while(num > 0) { remainder[i]=num%2; // mod function num=num/2; // divides original number 2 i++; // increases count upcoming for-loop length++; // increases length display digits } for(i=length-1;i>=0;i--) // prints out binary number in order (ignoring previous 0's) { printf("%ld",remainder[i]); } printf("\n"); // adds new line after binary number (formatting) } //================================================================================================ int main(char argc, char* argv[]) { long int num; //how take argv[0] , make useable variable??? printf("enter decimal number: "); //temporary until problem above solved scanf("%ld",&num); //temporary until problem above solved dectobinary(*num); // calling dectobinary function return 0; // program terminated }
hint1: if want change num
's value inside dectobinary()
function, have pass address in it. should call this:
dectobinary(&num);
then function's prototype this:
void dectobinary(long int *num)
so have modify function's body too. guess that's causes segmentation fault.
hint2: argc
stands arguments count, type isn't char
int
.
as @kerrek sb pointed out on comments, scanf(3)
function return value of type int
. it's considered wise check return value , handle possible error may occur.
argv[0]
name of executable. if want use first argument command line, it's stored in argv[1]
, , it's of type char *
. if want use number, can use 1 of these functions of stdlib.h
.
Comments
Post a Comment