【问题标题】:C : Write multiple arrays with one function.C : 用一个函数写多个数组。
【发布时间】:2015-01-20 21:08:10
【问题描述】:

我正在开发一个程序,该程序将编写一个问题,然后为 arduino 的串行监视器编写四个答案。 我的字符串是这样定义的:

   char question[] = "Question here";
   char answ_A[] = "answer1";
   char answ_B[] = "answer2";
   char answ_C[] = "answer3";
   char answ_D[] = "answer4";

我想编写一个打印函数并将数组名称传递给它。像这样:

void printarray(arrayname){
    int arraysize = (sizeof(arrayname) / sizeof(char));
    //insert loop to print array element by element
    }

有没有办法将数组的名称作为参数传递?我希望能够这样称呼它

printarray(question[]);

【问题讨论】:

  • 为什么不创建一个字符串数组并将问题及其答案放入该数组中?
  • @Meninx 我最终可能会这样做。不过,我想看看是否有办法做到这一点。

标签: c function arduino arguments arduino-uno


【解决方案1】:

您可以创建自己的结构(某种字典),但 C 没有任何工具可以按名称引用变量,而在编译时名称是未知的。

【讨论】:

    【解决方案2】:

    如果你想在函数中传递一个单维数组作为参数,你必须声明函数形式参数。

    /* 将指向数组的指针作为参数传递 */

    printArray( question) ;
    
    void printArray(char question[])
    {
    //process
    }
    

    【讨论】:

      【解决方案3】:

      不清楚您要的是什么;您想要一个功能在一次操作中同时打印问题和所有四个答案吗?

      如果是这样,您可以编写如下内容:

      char question[] = "Question here";
      char answ_A[] = "answer1";
      char answ_B[] = "answer2";
      char answ_C[] = "answer3";
      char answ_D[] = "answer4";
      
      /**
       * Set up an array of pointers to char, where each
       * element will point to one of the above arrays
       */
      const char *q_and_a[] = { question, answ_A, answ_B, answ_C, answ_D, NULL };
      
      printQandA( q_and_a );
      

      那么您的 printQandA 函数将如下所示:

      /**
       * Print the question and answers.  Use the pointer p to 
       * "walk" through the question and answer array.
       */
      void printQandA( const char **question )
      {
        const char **p = question; 
      
        /**
         * First element of the array is the question; print it
         * by itself
         */
        printf( "%s\n", *p++ );
      
        /**
         * Print the answers until we see the NULL element
         * in the array.
         */
         while ( *p )
           printf( "\t-%s\n", *p++ );
      }
      

      【讨论】:

      • 或者更多的模仿他想用的方式,我觉得他可以写void printQandA( const char **question ) { int arraysize = (sizeof(question ) / sizeof(char*));然后迭代……
      • @frarugi87: sizeof question / sizeof (char *) 不会给他数组中元素的数量。
      • @frarugi87:因为question参数只是一个指针; sizeof question 将返回指针对象的大小,而不是它指向的数组的大小。所以sizeof question / sizeof (char *) 将等同于sizeof (char **) / sizeof (char *)
      • @frarugi87:现在,起作用的是,如果他执行sizeof q_and_a / sizeof *q_and_a,并将该结果作为单独的参数传递给printQandA。由于q_and_a是一个数组表达式,sizeof q_and_a会返回整个数组的字节数。
      • 我认为 const 关键字的行为不同...谢谢您的解释 :)
      猜你喜欢
      • 2020-10-07
      • 2015-08-06
      • 2018-12-03
      • 1970-01-01
      • 2018-07-27
      • 1970-01-01
      • 2016-03-08
      • 2017-05-27
      • 2012-04-01
      相关资源
      最近更新 更多