变量不初始化

时间:2015-01-05 13:43:04

标签: c

当我尝试运行一段代码时,我一直收到这个错误,说这个变量正在被使用,虽然我已经宣布了,但是没有被初始化。

{
   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_search isn't being initialized尽管它在上面的代码中。

3 个答案:

答案 0 :(得分:2)

变化:

scanf("%d",number_search); 

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

答案 1 :(得分:1)

确实,number_search未初始化。

您对scanf(3)的来电是错误的。它应该是

scanf("%d", &number_search);

即使进行了更正,number_search仍然未初始化:scanf可能会失败(例如,如果您的用户在Linux上键入hello 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以获得优化。

答案 2 :(得分: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

给出的变量的地址