gpt4 book ai didi

c - 不读取 scanf() 之后的任何内容

转载 作者:行者123 更新时间:2023-11-30 17:10:06 25 4
gpt4 key购买 nike

我是 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]);
}
}
}
}

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

最佳答案

这一行

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++)

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

关于c - 不读取 scanf() 之后的任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33024456/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com