Ale*_*nis 3 c arrays function compound-literals function-call
当我尝试将数组发送到函数时,我得到一个错误.
这是我的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;
}
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是
mu_assert("error in test_Repetitive, Repetitive != 7", HistogramArray({1,2,3,4,5,6,7})== 7);
Run Code Online (Sandbox Code Playgroud)
它进入这个功能:
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;
Run Code Online (Sandbox Code Playgroud)
我基本上需要检查直方图函数中的计数器是否为7,有什么建议吗?
问题出在语法上HistogramArray({1,2,3,4,5,6,7}),这里{1,2,3,4,5,6,7}不是一个数组,它是一个支持初始化的括号列表.该HistogramArray()函数需要一个数组作为参数.
但是,您可以使用复合文字的语法
HistogramArray((int []){1,2,3,4,5,6,7})
Run Code Online (Sandbox Code Playgroud)
像数组一样使用它.
引用C11,章节§6.5.2.5,
后缀表达式由带括号的类型名称后跟一个大括号的初始值设定项列表组成,是一个复合文字.它提供了一个未命名的对象,其值由初始化列表给出.
和
如果类型名称指定了未知大小的数组,则大小由6.7.9中指定的初始化程序列表确定,复合文字的类型是已完成数组类型的类型.[...]
因此,这为您提供了一个未命名的数组,该数组使用括号括起的列表中的元素进行初始化.