Im a noob to programming in general, and one of the biggest confusions I've had is with pointers in C. They make perfect sense to me conceptually, but syntactically they're incredibly confusing. I was writing a program that takes in an unsigned short and prints it in binary one digit at a time, and it worked. But when I went to try to store it in a pointer to a char[] I couldn't get it to work. Ive looked at at least five different tutorials on pointers and from what I read, the code I have should work, but it doesn't.
I get no compile errors or even warnings, but all it prints is a single newline. I left in the code I had originally for just printing it one character at a time. If you uncomment the two printf statements in printBin(), you'll see that the loop runs properly and does what it's supposed to do.
I think this must be a simple problem, but I can't figure it out by myself. Thank you in advance for any help you can give me.
Code:#include <stdio.h>
char buffer[17];
char* printBin(unsigned short);
int main (int argc, const char * argv[]){
char* buffer2 = &buffer[0];
buffer2 = printBin(360);
printf("%s\n", buffer2);
return 0;
}
char* printBin(unsigned short number) {
int shift;
int bit;
char* binString = &buffer[0];
for (shift = 15; shift >= 0; shift--, binString++) {
bit = 1 << shift;
if ((number & bit) == bit) {
sscanf(binString, "1");
//printf("1");
}
else {
sscanf(binString, "0");
//printf("0");
}
}
//sscanf(binString, "hello");
return binString;
}