c - 转换类型导致错误
问题描述
我陷入了一个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...
有人可以点亮我,我该如何解决?我花了几个小时,仍然没有实现将它正确地传递给一个字符数组。
解决方案
推荐阅读
- spring - Can not use Kotlin to config Spring JPA Entity with Abstract Class
- powerbi - 将 Power BI 数据源中的单行数据拆分为多行
- java - Java - 泛型 - 在泛型指定对象中转换泛型对象不起作用
- reporting-services - 使用 ODBC 将数据源添加到报表生成器
- extjs - ExtJS 和 FontAwesome:屏幕阅读器兼容性
- c - 格式化字符串的大小
- ruby-on-rails - 在 Rspec 请求规范中设置会话变量
- mongodb - 为什么我的数据库中会出现空数组?
- php - Laravel:Swift_TransportException:无法与主机建立连接
- odoo - 创建发票时如何修改销售订单行?