如何正确地将数组作为函数参数传递?

How to properly pass an array as a function argument?

当我尝试将数组发送到函数时出现错误。

这是我的minunit测试程序:

#include "minunit.h"
#include "calc.h"
#include <stdio.h>

int tests_run = 0;

 static char * test_Repetitve() {
     mu_assert("error in test_Repetitive, Repetitive != 7", HistogramArray({1,2,3,4,5,6,7})== 7);
     return 0;
 }

 static char * all_tests() {
         mu_run_test(test_Repetitive);
     return 0;
 }

 int main(int argc, char **argv) {
     char *result = all_tests();
     if (result != 0) {
         printf("%s\n", result);
     }
     else {
         printf("ALL TESTS PASSED\n");
     }
     printf("Tests run: %d\n", tests_run);

     return result != 0;
 }

我遇到问题的行是

mu_assert("error in test_Repetitive, Repetitive != 7", HistogramArray({1,2,3,4,5,6,7})== 7);

它进入这个函数:

    int HistogramArray(int one[])
{
    int arrchk[TWENTY+ONE] = { ZERO }, i, j,counter=0;//arrchk is an array that counts how many times the number appears.
    for (i = ZERO; i<N; i++)
        arrchk[one[i]]++;
    for (i = ZERO; i<TWENTY+ONE; i++)
    {
        if (arrchk[i] != ZERO) 
                        {
                         printf("the number is %d ", i);//printing the histogram.
                          counter++;
                        }
        for (j = ZERO; j<arrchk[i]; j++)
        {
            printf("*");

        }
        if (arrchk[i] != ZERO)printf("\n"); 
    }
return counter;

我基本上需要检查直方图函数中的计数器是否为 7,有什么建议吗?

问题出在语法 HistogramArray({1,2,3,4,5,6,7}) 上,这里 {1,2,3,4,5,6,7} 本身不是一个数组,它是一个用大括号括起来的初始化列表。 HistogramArray() 函数需要一个数组作为参数。

但是,您可以使用 compound literal

的语法
  HistogramArray((int []){1,2,3,4,5,6,7})

像数组一样使用它。

引用 C11,章节 §6.5.2.5,

A postfix expression that consists of a parenthesized type name followed by a braceenclosed list of initializers is a compound literal. It provides an unnamed object whose value is given by the initializer list.

If the type name specifies an array of unknown size, the size is determined by the initializer list as specified in 6.7.9, and the type of the compound literal is that of the completed array type. [...]

因此,这为您提供了一个未命名的数组,该数组使用大括号括起来的列表中的元素进行了初始化。