没有读过scanf()的任何内容

时间:2015-10-08 19:32:50

标签: c

我是C的新手并且想知道为什么我没有得到任何类型的输出。我试图让我的程序将十六进制数转换为二进制数。

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

int* hex2binary(int hex_array[], int input_array_size, int* return_array_size) {
  int hex_size = input_array_size;
  int binary_array_size = 4 * hex_size;
  int *binary_array = (int*) malloc(binary_array_size * sizeof(int));
  int hex_index, binary_index;
  for (hex_index = 0; hex_index < hex_size; hex_index++) {
    int hex_num = hex_array[hex_index];
    binary_index = hex_index * 4;
    int bit_count;
    for (bit_count = 3; bit_count <= 0; bit_count--) {
      binary_array[binary_index + bit_count] = hex_num % 2;
      hex_num = hex_num / 2;
    }
    hex_index++;
  }
  *return_array_size = binary_array_size;
  return binary_array;
}

int main() {
  char baseString[11];
  int count = 0;
  int i, j;
  int original, wanted;
  int size;

  printf("Welcome to use this number base converter program.\n");
  printf("Please input the original base: ");
  scanf("%d", &original);
  printf("Please input a base-%d number with more more than 10 digits: ",
      original);
  scanf("%s", baseString);

  while (baseString[count] != '\0')
    count++;

  int *baseNumber = (int*) malloc(count * sizeof(int));

  for (i = 0; i < count; i++) {
    baseNumber[i] =
        baseString[i] <= '9' ? baseString[i] - '0' : baseString[i] - 'A' + 10;
  }

  int* result_array;
  printf("Please input the target base: ");
  scanf("%d", &wanted); //doesn't read anything past this point
  printf("Target base: %d", wanted);

  if (original == 16) {
    if (wanted == 2) {
      result_array = hex2binary(baseNumber, count, size);
      for (j = 0; j < size; j++) {
        printf("Result: %d", result_array[j]);
      }
    }
  }
}

我知道它不会有困难,但我似乎无法弄清楚为什么它甚至不会产生某种输出。

1 个答案:

答案 0 :(得分:0)

这一行

result_array = hex2binary(baseNumber, count, size);

不正确,因为此函数需要指针参数

int* hex2binary(int hex_array[], int input_array_size, int* return_array_size)

所以应该像这样调用

result_array = hex2binary(baseNumber, count, &size);   // note the &

然后是后续循环

for (j = 0; j < size; j++)

将不再使用未初始化的变量 size