2016-07-23 43 views
0

我不明白爲什麼每次我嘗試輸入名稱值時都會收到此異常。將函數中的數組傳遞給scanf時發生異常

這是我得到的異常,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]); 
} 
+1

請提供一個能夠重現bug的[minimal example](http://stackoverflow.com/help/mcve) – wasthishelpful

+0

在編程生涯的這個階段,您應該假設如果編譯器生成警告,在你的代碼中有一個錯誤。即使在未來幾年內,情況仍然會如此之多(100次中的99次)。 –

回答

1

你會錯在這裏

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

你的功能askuser需要char[][]類型的第一個參數,但你逝去的char類型的參數,這對於所有傳遞的參數

因此變爲真對askuser()的更正呼叫應該是

counter = askUser(name, hourlyRate, hoursWorked); 

相同的錯誤重複兩次以上主 請在運行代碼之前查看編譯器警告。