简体   繁体   English

变量未初始化

[英]Variable not initializing

I keep getting this error when I try to run a piece of code say that the variable is being used which isn't initialized, despite I've declared it. 当我尝试运行一段代码时,尽管我已经声明了变量,但仍未初始化,但我一直收到此错误。

{
   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);
  }

it's saying that the int number_search isn't being initialized despite it being in the code above. 就是说,尽管int number_search在上面的代码中,但isn't being initialized

Change: 更改:

scanf("%d",number_search); 

to

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

Indeed, number_search is not initialized. 实际上, number_search尚未初始化。

And your call to scanf(3) is wrong. 而且您对scanf(3)的调用是错误的。 It should be 它应该是

scanf("%d", &number_search);

and even with that correction, number_search is still uninitialized: scanf can fail (eg if your user types hello or Ctrl D on Linux) and you should test the result of scanf (number of successfully read items), at least: 即使进行了更正, number_search仍未初始化: scanf可能会失败(例如,如果您的用户在Linux上键入helloCtrl D ),并且您应该测试scanf的结果(成功读取的项目数),至少:

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

I believe that you should always explicitly initialize local variables (if that initialization happens to become useless, the compiler would optimize it out), like 我相信您应该始终显式初始化局部变量(如果初始化碰巧变得无用,则编译器会对其进行优化),例如

int number_search = 0;

PS. PS。 You should compile with all warnings and debug info, eg gcc -Wall -Wextra -g ; 您应该编译所有警告和调试信息,例如gcc -Wall -Wextra -g ; once you are sure of not having bugs, add -O2 to get optimizations. 一旦确定没有错误,请添加-O2以获得优化。

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

This should be 这应该是

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

and

scanf("%d", &number_search);

Scan to the address of the variable which is given by &number_search 扫描到&number_search给定的变量的地址

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM