有没有办法在这段代码中声明变量 a 和 b?

问题描述

我试图在 main 中调用一个函数,以便我的代码将通过我的代码的所有部分执行。现在,当我在 main 中调用 compare_quads 时。我收到 a 和 b 未声明的错误代码。但我的问题是我不知道如何声明变量,因为我已经在我认为可行的代码顶部声明了函数和变量。如果我尝试在 main 中声明变量,例如

const void *a;
const void *b;

然后在编译我收到时,警告 a 在此函数中未初始化使用,与 b 类似。

这是我的代码

//declare libraries
  #include <string.h>
  #include <stdio.h>
  #include <stdlib.h>
 
  //declare other functions/files to be used in the program
  void print_fun(void);
  void read_fun(void);
  static int compare(int arg,unsigned char networks[arg][4]);
  int compare_quads(const void *a,const void *b);
 
 
  //read command line input and store the information
  int main(int argc,char** argv){
      //declar variable
      int arg = 0;
 
      //make argv into an int
      arg = atoi(argv[1]);
      //assign size to networks
       unsigned char networks[arg][4];
 
      //assign input to networks
      for (int j =0; j<1; ++j){
          if(argc == 1)
               {
                  printf("ERROR ERROR,you messed up\n");
              }
  
         else
         {
          // hold network addresses in a 2-d array,with 4 unsigned char
 
              for(int k = 0; k<arg; k++){
                  for (int i =0; i<4; i++){
 
                  scanf("%hhu.",&networks[k][i]);
                  //checks to see if scanf was working properly
                 // printf(" %hhu",networks[k][i]);
 
              }
                  //printf("\n");
              }}}
 
 
      compare_quads(a,b);
      compare(arg,networks);
 
  return(0);
  }
 
 
  int compare_quads( const void *a,const void *b) {
      return memcmp (a,b,4);
  }
 
 
  static int compare(int arg,unsigned char networks[arg][4])
  {
 
  qsort(networks,arg,sizeof(networks[0]),compare_quads);
 
      for (int k = 0; k< arg; k++){
          printf("%d.%d.%d.%d\n",networks[k][0],networks[k][1],networks[k][2],networks[k][3]);
          }
          return 0;
 }

我对 c 很陌生,所以如果您需要任何说明,请告诉我。谢谢。

确切的警告是

单元化

main.c: In function ‘main’:
main.c:47:19: error: ‘a’ undeclared (first use in this function)
   47 |     compare_quads(a,b);
      |                   ^
main.c:47:19: note: each undeclared identifier is reported only once for each function it appears in
main.c:47:22: error: ‘b’ undeclared (first use in this function)
   47 |     compare_quads(a,b);
      |                      ^

当 const void *a;用于初始化。

main.c: In function ‘main’:
main.c:48:5: warning: ‘a’ is used uninitialized in this function [-Wuninitialized]
   48 |     compare_quads(a,b);
      |     ^~~~~~~~~~~~~~~~~~~
main.c:48:5: warning: ‘b’ is used uninitialized in this function [-Wuninitialized]

编辑 我正在接收一个输入文件,该文件具有不同数量的网络地址行,如

139.72.16.202

我将值存储在大小为 [由 arg 设置的变量][4] 的数组中

然后在 main 函数之后,其余的我用来按列对代码进行排序。排序功能运行良好。

解决方法

指向 const submitButton = screen.queryByText('submit') expect(submitButton).toBeNull() // it doesn't exist expect(submitButton).not.toBeNull() // it exist 函数的指针作为比较函数传递给 compare_quads 函数,因此它会被 qsort 内部调用。

因此,您无需在 qsort 函数中调用 compare_quads。将它传递给 main 就足够了。