2015-01-05 190 views
-1

當我嘗試運行一段代碼時,我一直在收到這個錯誤,說這個變量正在被使用,雖然我聲明瞭它沒有被初始化。變量不初始化

{ 
    FILE *fptr; 
    int length; 
    int number_search; 

    struct student 
    { 
     char surname[15]; 
     char initials[6]; 
     char title[4]; 
     int student_number; 
     char module_name[25]; 
     char module_code[7]; 
     int assesment_mark; 
     int exam_mark; 
     int tuition_fee; 
    }; 

struct student record_student; 
struct student *student_ptr; 
student_ptr=&record_student; 
length=sizeof(struct student); 

printf("2 has been called\n"); 
printf("Enter module code: \n"); 
scanf("%s", module_code); 
clear_buffer(module_code); 
printf("%s\n",module_code); /*Test the string entered is 6 charaters, AB1234 format*/ 

    if (! modcheck(module_code)) /*Change this fucntion to a differnt one to check correct format*/ 
{ 
    printf("Invalid input\n"); 
    } 
    else  
    { 
     printf("input ok\n"); 
     printf("Enter Student Number: \n"); 
     scanf("%d",number_search); 
    } 

它說,int number_searchisn't being initialized,儘管它的代碼是以上。

回答

2

變化:

scanf("%d",number_search); 

scanf("%d", &number_search); 
      //^See here the address operator 
1

事實上,number_search未初始化。

而您致電scanf(3)是錯誤的。它應該是

scanf("%d", &number_search); 

,甚至與校正,number_search仍然未初始化:scanf可能失敗(例如,如果您的用戶類型helloLinux上的Ctrl鍵d),你應該測試的scanf(數的結果成功讀取的物品),至少:

if (scanf("%d", &number_search) != 1) { 
    perror("number_search input failure"); exit(EXIT_FAILURE); 
} 

我認爲,你應該始終明確初始化局部變量(如果初始化恰好變得毫無用處,編譯器會優化它),就像

int number_search = 0; 

PS。您應該編譯所有警告和調試信息,例如gcc -Wall -Wextra -g;一旦確定沒有錯誤,請添加-O2以獲得優化。

0
printf("Enter module code: \n"); 
scanf("%s", module_code); 

這應該是

printf("Enter module code: \n"); 
scanf("%s", student_ptr->module_code); 

scanf("%d", &number_search); 

掃描到其通過&number_search

給出的變量的地址