2015-01-05 197 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

给出的变量的地址