2017-05-07 101 views
0

有人可以給我一個提示,爲什麼這不是打印數組?我不知道我的打印功能有什麼問題。在將其他部分添加到我的代碼之前,我想確保它正常工作。我猜我沒有正確設置陣列&這就是爲什麼沒有打印出來。打印用戶輸入數組

#define NUMSTU 50 

#include <stdio.h> 

//function prototype 
void printdata(); 

//Global variables 

int stuID[NUMSTU]; 
int stuCount; 
int totStu; 

int main() 
{ 
    int stuCount = 0; 
    int totStu = 0; 
    int studentID; 
    //Prompt user for number of student's in class 

    printf("Please enter number of student's in class:"); 
    scanf ("%d", &totStu); 

    for (stuCount = 0; stuCount <totStu; stuCount++) 
    {  
    //Prompt user for student ID number 

    printf("\n Please enter student's ID number:"); 
    scanf("%d", &studentID); 
    stuID[NUMSTU] = studentID; 

    } 

//Call Function to print data 
printdata(); 

return 0; 
}//end main 


void printdata(){ 

//This function will display collected data 
//Input: Globals stuID[NUMSTU] 
//Output: none 



//Display column headers 
printf("\n\n stuID\n"); 

//loop and display student ID numbers 
for (stuCount = 0; stuCount <totStu; stuCount++){ 
printf("%d", stuID); 
} 
} 
+2

'stuID [NUMSTU] = studentID;'有未定義的行爲。你正在寫入一個超出界限的元素。 – melpomene

+1

'printf(「%d」,stuID);'有未定義的行爲。 'printf''%d'接受一個'int',但你傳遞一個'int *'。 – melpomene

+0

你有兩個名爲'totStu'的變量。其中只有一個具有非零值。 – melpomene

回答

1

這裏有多個錯誤。 首先,你應該得到一個出界異常,因爲這條線 (在更高層次的編程語言)的:

stuId[NUMSTU] = studentId; 

stuId是有NUMSTU初始長度的數組。 即使您在NUMSTU中嘗試訪問它,即使它只有0(NUMSTU-1)之間的可訪問插槽 。

你可能想要做這件事情:

stuId[stuCount] = studentId; 

,並在打印,你只打印陣列的位置再次 又一遍。相反的:

print("%d", stuId); 

做:

print("%d", stuId[stuCount]); 

噢,和第三個錯誤,在這裏:

int stuCount = 0; 
int totStu = 0; 

stuCounttotStu已經被定義爲全局變量 (即每個功能可以訪問它們)。 你正在做的是定義具有相同名稱的新變量, 但不能被其他函數訪問。 所以你應該決定他們是全球性的還是本地的。 無論如何,你應該將其更改爲:

stuCount = 0; 
totStu = 0; 

現在,它應該工作。

+0

謝謝 - 現在正在工作。 –

+0

這是C;你不會得到'超出界限'的例外 - 你會得到任何你得到的,這可能是一個例外,或者它可能是編譯器決定的其他任何東西。 –

+0

那麼,我編輯它。希望現在好了。 – blahh