Search code examples
cprintfc-strings

Unable to printf() char array in c


I don't seem to be understanding how printf() formats the output of char arrays in C. I have a bit of code whose purpose is to translate an integer into a string of binary characters, and print it. The code works up to the point where I go to print the string returned from integerToString(), because it doesn't print the contents of the string.

I've checked gdb to ensure that both res and str contained an array of the correct values before the printf() call. I've also tried printing *res instead of just res, but that returns (null). What am I missing? Is there something about pointers that I am not grasping?

Thanks much in advance.

#include<stdio.h>
#include<stdlib.h>

int main () {   
  printf("Please enter a positive integer: ");
  unsigned int input;

  scanf("%d", &input);

  char* res = integerToString(input);
  printf("Represented in binary that integer is: %s\n", res);
}

char* integerToString(unsigned int number){
  unsigned int value = number; 

  char* str;
  str = malloc(33); //32 bits for the string, +1 null value on the end

  unsigned int i = 31;

  while (i > 0){
    str[i] = value % 2;
    value /= 2;
    i--;
  }
  str[32] = '\0';
  return(str); 
}

Solution

  • This bit str[i] = value % 2; is assigning 0 or 1 to characters in your array, but the printf is expecting a string, so you want to assign the ASCII character for zero or one. You are currently assigning a mixture of nulls and SoH (start of header, control-A). Since ASCII one is one more than ASCII zero:

    str[i] = value % 2 + '0'; /* ASCII zero plus this bit's value */
    

    In addition, the loop stops at i = 0, so str[0] is never set. Luckily/unluckily it must contain the binary value 0.