C:用一个函数写多个数组。

C : Write multiple arrays with one function.

我正在开发一个程序,该程序将编写一个问题,然后向 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[]);

要将一维数组作为函数参数传递,必须声明函数形参。

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

printArray( question) ;

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

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

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

如果是这样,你可以这样写:

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