3

When I try to send an array in to the function I get an error.

This is my minunit test program:

#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;
 }

The line that I have problem with is

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

and it goes in to this function :

    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;

I basically need to check if the counter is 7 in the Histogram Function, any suggestions?

MD XF
  • 7,860
  • 7
  • 40
  • 71
Alex Kreinis
  • 147
  • 7

1 Answers1

5

The problem is with the syntax HistogramArray({1,2,3,4,5,6,7}), here {1,2,3,4,5,6,7} is not an array on it's own, it's a brace-enlosed list of initializers. The HistogramArray() function expects an array as argument.

You can however, use it with a syntax of compound literal

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

to use it like an array.

Quoting C11, chapter §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.

and

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. [...]

So, this provides with you with an unnamed array which is initialized with the elements in the brace enclosed list.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • @AlexKreinis Strictly speaking, this is not *passing an array as a function argument*, this is *writing an array literal*. Arrays cannot be passed to functions. What gets passed dto the function in tbis case is a pointer, not an array. It will still work for you but ideally you should know the difference. – n. m. could be an AI Jan 02 '18 at 17:25