c - 程序崩溃并显示 0xC0000005

标签 c

我一直在尝试运行我的代码,但总是以错误代码 0xC0000005 结束

#include <stdio.h>
#include <math.h>

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”,金属,电阻);”或最后一次 scanf 之后的任何 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,因为您没有这样做传递单个字符,而不是数组(实际上,指向其第一个元素的指针,因为数组“衰减”)。

关于c - 程序崩溃并显示 0xC0000005,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42289031/

相关文章:

无法将一个 .wav 的开头(前 64 个字节)复制到一个空的

c 指针 - 警告格式 '%x' 需要类型为 'unsigned int' 的参数

c - C 中的 fgets 函数和文件处理

c - 外部结构和多个 header

c - 如何向标准信号处理程序添加代码?

c - 打印空格数

c - 为什么数组元素存储的是 n-1 而不是 n 的值

c - 父子进程中的管道、 fork 和​​轮询

c - Unix - 如何获取域名的IP地址?

c++ - char** vs char* c[] 用于访问字符串数组