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

时间:2015-01-20 21:08:10

标签: c function arduino arguments arduino-uno

我正在开发一个程序,它会写一个问题,然后是arduino的串行监视器的四个答案。 我的字符串定义如下:

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

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

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

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

printarray(question[]);

3 个答案:

答案 0 :(得分:0)

您希望将一维数组作为参数传递给函数,您必须声明函数形式参数。

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

传递
printArray( question) ;

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

答案 1 :(得分:0)

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

答案 2 :(得分:0)

你所要求的并不是很清楚;你想要一个功能在一次操作中打印问题和所有四个答案吗?

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

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