【问题标题】:exception when passing array in function to scanf将函数中的数组传递给scanf时出现异常
【发布时间】:2016-07-23 07:37:05
【问题描述】:

我不明白为什么每次尝试输入名称值时都会收到此异常。

这是我得到的异常,Program3.exe 中在 0x0F59B211 (ucrtbased.dll) 处引发的异常:0xC0000005:访问冲突写入位置 0xFFFFFFCC。

如果有这个异常的处理程序,程序可以安全地继续。

我是c新手,所以请彻底解释。

#include <stdio.h>
#include <string.h>

int askUser(char name[5][16],float hourlyRate[5],float hoursWorked[5])
{
    int counter = 0;

for (int i = 0; i < 5; i++)
{

    printf("enter name: ");
    scanf_s("%15s", name[i], 16);
    if (strcmp(name[i], "-1") == 0)
        break; 
    printf("enter hourly rate: ");
    scanf_s("%f", &hourlyRate[i]);
    if (hourlyRate[i] == -1)
        break;
    printf("enter hours worked: ");
    scanf_s("%f", &hoursWorked[i]);
    if (hoursWorked[i] == -1)
        break;

    counter++;
}

return counter;
}

void main()
{
const float OVERTIMEHOURS = 40.0f;
const float OVERTIMERATE = 1.5f;
const float TAX = 0.20f;
char name[5][16] = { "", "", "", "", "" };
float hourlyRate[5] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f };
float hoursWorked[5] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f };
float amountPaid[5] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f };
float basePay[5] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f };
float overPay[5] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f };
float taxPaid[5] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f };
float netPay[5] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f };
float overTime[5] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f };
float totalPaid = 0.0f;

int counter = 0;


counter = askUser(name[5][16], &hourlyRate[5], &hoursWorked[5]);
}

【问题讨论】:

  • 请提供minimal example 来重现您的错误
  • 在您的编程生涯的这个阶段,您应该假设如果编译器生成警告,您的代码中就有错误。即使再过几年,这种情况仍然会经常发生(100 次中有 99 次)。

标签: c function parameters


【解决方案1】:

你错了

counter = askUser(name[5][16], &hourlyRate[5], &hoursWorked[5]);

您的函数askuser 需要char[][] 类型的第一个参数,但您传递的是char 类型的参数,这适用于所有传递的参数

所以对askuser() 的更正调用应该是

counter = askUser(name, hourlyRate, hoursWorked);

同样的错误在 main 中又重复了两次 请在运行代码之前查看编译器警告。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-10
    • 1970-01-01
    • 1970-01-01
    • 2015-05-11
    • 2017-07-29
    • 2014-12-10
    相关资源
    最近更新 更多