Interesting array problem
Hello, I trying to print the byte strings for two alphanumeric characters (required to store this using dynamically allocated memory) that are input by a user, using two character arrays. When I print the results, they are valid, yet the second array much to my suprise prints its binary string along with the binary string for the first character input as well! Can someone help elaborate on why this is happen (I highly suspect it has something to do with how I am managing memory). I am justing getting back into the swing of using c. :(
Code:
#include <stdio.h>
#include <stdlib.h>
void calculateBitString(char, char[]);
int main() {
char* charPtr = (char*)malloc(2);
char bitString1[8];
char bitString2[8];
printf("Please input an alphanumeric character: ");
scanf("%c", &charPtr[0]);
fflush(stdin);
//printf("Please input another alphanumeric character: ");
scanf("%c", &charPtr[1]);
calculateBitString(charPtr[0], bitString1);
calculateBitString(charPtr[1], bitString2);
printf("%s\n", bitString1);
printf("%s\n", bitString2);
return 0;
}
void calculateBitString(char input, char string[8]){
unsigned char temp;
unsigned char mask =0x80;
int i;
for(i= 0; i < 8 ; i++){
temp = input & mask;
if (temp == 0)
string[i]= '0';
else
string[i]='1';
mask = mask>>1;
}
}