问题描述
我写了下面的程序:
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
void inttobusn(int val, int n, char* bus)
{
int i;
unsigned int digit;
for (i=0; i < n; i++) {
digit = pow(2, (n-1-i));
if (digit <= val) {
val -= digit;
bus[i] = '1';
//printf("hello %c",bus[i]);
} else {
bus[i] = '0';
}
}
}
main(){
char* bus;
inttobusn(37,8,bus);
int i=0;
//printf("%s",bus);
for(i=0;i<12;i++){
printf("%c",bus[i]);
}
}
但在运行它不打印数组的元素公交
。它不打印任何东西。我无法弄清楚什么是错的。请可能有人指出?
But on running it doesn't print the elements of the array bus
. It doesn't print anything. I am unable to figure out what is wrong. Please could someone point out?
推荐答案
您code是越野车!你不分配的总线[]
数组的内存,并且在垃圾位置如巴士试图访问值[I] = 0;
- 在ç未定义行为
标准,未定义意味着你不能predict你如何code将表现在运行时。
Your code is buggy! you don't allocate memory for the bus[]
array, and are trying to access values at garbage location as e.g bus[i] = 0;
-- Undefined Behavior in C
standard, Undefined means you can't predict how your code will behave at runtime.
这code编译因为语法明智的code是正确的,但在运行时,操作系统会检测到非法的内存访问,并可以终止你的code。 (有趣的:作为操作系统由过程检测内存侵权问题 - 有效内存的无效访问,得出:SIGSEGV并获得无效的地址给:SIGBUS)。在最坏的情况下,你的程序似乎没有执行任何故障,产生的垃圾结果。
This code compiled because syntax-wise the code is correct but at runtime the OS will detect illegal memory access and can terminate your code. (interesting to note: as OS detects memory right violation by a process -- An invalid access to valid memory gives: SIGSEGV And access to an invalid address gives: SIGBUS). In the worst case your program may seem execute without any failure, producing garbage results.
要简单地纠正它定义公交
阵列字符总线[N];
其他分配的内存使用动态无效* malloc的(为size_t大小);
To simply correct it define bus
array as char bus[N];
else allocated memory dynamically using void* malloc (size_t size);
此外,建议您从@Lochemage和@Ran入住Eldan:
Additionally, suggestion to your from @Lochemage and @Ran Eldan:
您需要使用特定的大小来声明总线,如字符总线[12]
。它必须至少足够大,以适应 12
字符,因为你在年底环是通过许多迭代(你可以检查你的code。与该工作建议@ )。
You need to declare bus with a specific size, like char bus[12]
. It has to be at least large enough to fit 12
chars because your for loop at the end is iterating through that many (and you can check your code working with this suggestion @codepade).
也没有返回类型为的main()
在code,它应该是 INT主要(无效)
。
Also there is no return type to main()
in your code, its should be int main(void)
.
这篇关于C程序不打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!