I realize a segmentation fault occurs when trying to access restricted memory. However, I have no clue why this is happening. Here's my code. It's converting a decimal number to a binary number.
Code:
void tobinary(int x, char s[]);
int main() {
char hold[4];
tobinary(5, hold);
return 0;
}
void tobinary(int x, char s[]){
int k=0,n=0;
int neg=0;
int sLength=sizeof(s);
int remain;
int temp[sLength];
if (x<0) {
x=-x;
neg=1;
}
do {
remain=x%2;
x=x/2;
temp[k++]=remain+'0';
} while (x >0);
if(neg) {
temp[k++]='-';
}
else {
temp[k++]=' ';
}
while (k>=0) {
s[n++]=temp[--k];
}
s[n-1]=0;
k=0;
while (k<4) {
printf("%d", s[k]);
k++;
}
}