简体   繁体   中英

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); 
}

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.

As cupcake points out, you have problems in you conversion, but I think the reason for the null is the missing declaration for integerToString. Because the definition of this function is after its use, C will assume that it returns an int -- this is a default action. If you are on a 64 bit system this will throw away many of the returned bits. You can resolve this by either adding a forward declaration, or reversing the order of the two functions in your source. The latter is an idiom adopted by many C programmers to avoid the clumsy forward declarations.

Usually, your compiler will complain when it later finds a function definition which doesn't match the one it assumed. If your compiler doesn't do this, you really should get one that does. There are lots of free compilers available these days, and really no reason to put up with a lousy one.

If you ignored your compiler complaining about this, then you shouldn't have.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM