Reputation:
I'm currently messing around with a project in C that will take in two 8-bit binary numbers and convert them to decimal values. I have a good understanding of the bit-wise operators in C and how they treat numbers, my question is one that revolves around syntax.
ATM my program is very simple:
int main() {
char *inp1;
char *inp2;
unsigned long binNum1;
unsigned long binNum2;
printf("Enter the first binary number: ");
scanf("%s", inp1);
printf("Enter the second binary number: ");
scanf("%s", inp2);
binNum1 = strtoul(inp1, NULL, 2);
binNum2 = strtoul(inp1, NULL, 2);
unsigned long orVal = binNum1 | binNum2;
unsigned long andVal = binNum1 & binNum2;
unsigned long exclVal = binNum1 ^ binNum2;
printf("Your or value is: %lu", orVal);
printf("Your and value is: %lu", andVal);
printf("Your exclusive value is: %lu", exclVal);
return 0;
}
Essentially, I just want to get the value of ORing, ANDing, and EXCLing the two decimal values of each binary number. However, I get a segmentation fault when I run this. I'm pretty sure this is due to syntax, but I can't find much online for this type of problem.
Upvotes: 0
Views: 1013
Reputation: 34585
With these lines
char *inp1;
char *inp2;
...
scanf("%s", inp1);
scanf("%s", inp2);
you have not assigned any memory to inp1
or to inp2
. The pointers are uninitialised and this is the probable cause of the segfault.
To simplify it you could do it like this:
char inp1[100];
printf("Enter the first binary number: ");
if(scanf("%99s", inp1) != 1) {
return 1;
}
and similarly for inp2
.
Upvotes: 5