首页 > 解决方案 > 转换类型导致错误

问题描述

我陷入了一个univ项目,如下所示:我在知道输入格式之前就在做,所以我开始用%s阅读它,它是一个char [32]。然后当项目发布时,我意识到我需要将输入读取为 int。所以现在我开始将它读为 int,现在我不想再制作我制作的所有其他函数,并且它们将参数作为字符数组(char [32])接收。所以我做了一个函数来将 int 值转换为 int*,因为我不能返回 char[32]。因此,我在 main 上做了一个简单的 for 将 int* 中的值传递给 char[32]。问题是,当我在 main 上打印它时,我看到的值完全相同,但是当我将这个新的 char[32] 传递给我的函数时,我现在遇到了一个错误。我想我的问题是因为 '\0' 或类似的东西。

下面是一个简单的演示:

int* convert_dec_to_bin(int n){
    printf("\n");
    int i, j, k;
    int *bits;
    bits = (char*)malloc(32*sizeof(int));
    for(i = 31, j = 0; i >= 0; --i){
        printf("%d", n & 1 << i ? 1 : 0);
        if(n & 1 << i){
            bits[j] = 1;
        }else{
            bits[j] = 0;
        }
        j++;
    }
    printf("\n");
    return bits;
}


int main(){


    int i, k, instructionNameInt;
    char type;
    int *bits;
    char bitsC[32];
    //char instructionBinary[32]; I was reading like this before, ignore this line
    int instructionBinary; //Now I read like this
    scanf("%d", &instructionBinary);
    bits = convert_dec_to_bin(instructionBinary); //This is a function where I pass the int decimal input to 32 bits in binary as int*.

    //Making probably the wrong conversion here, I tried to put '\0' in the end but somehow I failed
    for(k = 0; k < 32; k++){
        bitsC[k] = bits[k];
    }
    printf("\n");


    type = determine_InstructionType(bitsC);

    printf("TYPE: %c\n", type);

    instructionNameInt = determine_InstructionName(bitsC, type);

    And several other functions...

有人可以点亮我,我该如何解决?我花了几个小时,仍然没有实现将它正确地传递给一个字符数组。

标签: c

解决方案


推荐阅读