程序崩溃与0xC0000005
我一直试图运行我的代码但总是以错误代码0xC0000005结束
#include #include void calculate_resistance(char metal, int length, int diameter, float resistivity); int main() { int length, diameter; float resistivity; char metal; printf("Enter the name of the metal: "); scanf("%s", &metal); printf("Enter the resistivity: "); scanf("%f", &resistivity); printf("Enter the length: "); scanf("%d", &length); printf("Enter the diameter: "); scanf("%d", &diameter); calculate_resistance(metal, length, diameter, resistivity); return 0; } void calculate_resistance(char metal, int length, int diameter, float resistivity) { float radius = diameter / 2; float area_of_wire = (M_PI) * pow(radius,2) * length; float resistance = resistivity * length / area_of_wire; printf("Resistivity of %s is %f", metal, resistance); }
我发现如果我注释掉“printf(”%s的电阻率是%f“,金属,电阻);” 或者在最后一次扫描后的任何printf,它不会崩溃,错误代码为0xC0000005
char metal;
声明一个char
。 它只能存储一个字符。 您想要存储一组字符,即字符串 。 所以用
char metal[50]; /* Can store a max of 49 chars +1 for the \0 */
在那之后,省略&
scanf("%s", &metal);
因为数组的名称已转换为指向其第一个元素的指针。 为了增加安全性,可以防止格式说明符中的长度修饰符表示最大字符数减1(为NUL终止符保留1个空格):
scanf("%49s", metal);
此外,您应该提供更多错误检查,并通过查看其返回值来检查所有scanf
是否成功。 不要忘记在函数声明和定义中将char metal[]
更改为char metal[]
或char* metal
,因为您没有传递单个字符,而是传递数组(实际上,指向其第一个元素的指针因为数组“衰变” “)。
char metal; printf("Enter the name of the metal: "); scanf("%s", &metal);
此代码调用未定义的行为。 您正尝试在一个char
变量中存储字符序列。 您应该使用%c
格式说明符或字符数组。
可变金属是炭。 这只包含1个字符。 你需要持有一个字符数组。
char metal[100];
当然100可能不适合您的情况,但使用char
和%s
进行scanf
和printf
会导致问题。