0

I frequently use the following convention to inform client code that a function requires an argument of an array with defined size:

/* File foo.h */
int foo (int arg[10]);

The message I want to give to client code is that they must provide an array of type int with 10 positions.

I am aware that it is not very usual, so I came here to ask: Am I missing any side effect of this convention ? Is it anyhow harmful?

Thank!

Felipe Lavratti
  • 2,887
  • 16
  • 34

3 Answers3

2
struct arrayContainerTen{
  int data[10];
}
void aFunction(struct arrayContainerTen *pAnArray)
{
    size_t size = sizeof(pAnArray->data);
}
main()
{
     arrayContainerTen anArray;
     aFunction(&anArray);
}
user3528438
  • 2,737
  • 2
  • 23
  • 42
2

If you want to insist on getting an array of size 10, you can use:

int foo (int (*arg)[10]);

The ill-side effects of this are:

  1. In the function, you have to use:

    (*arg)[index] 
    

    instead of just

    arg[index]
    
  2. The calling function must use:

    int array[10];
    foo(&array);
    

    instead of

    int array[10];
    foo(array);
    
  3. You cannot use an array that has more than 10 elements.

    int array[20];
    foo(&array);   // Not OK.
    
  4. You cannot use a malloced array.

    int* array = malloc(sizeof(int)*10);
    foo(array);   // Not OK.
    

Now pick the solution that is least harmful.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • At least, it's safe to cast the pointer to the array if it's too big or allocated: for 3. : `foo((void *)array)` or `foo((int(*)[])array)`; for 4.: `foo((int(*)[])array)` etc. – mafso Mar 10 '15 at 18:40
1

There's no harm in writing it like this. But just be aware that the compiler will not enforce the requirement. A declaration like that is treated by the compiler as if you'd written.

int foo(int *arg);
Barmar
  • 741,623
  • 53
  • 500
  • 612