Felipe Lavratti
Felipe Lavratti

Reputation: 2967

Function parameter as array with declared size

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!

Upvotes: 0

Views: 184

Answers (3)

R Sahu
R Sahu

Reputation: 206617

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.

Upvotes: 2

user3528438
user3528438

Reputation: 2817

struct arrayContainerTen{
  int data[10];
}
void aFunction(struct arrayContainerTen *pAnArray)
{
    size_t size = sizeof(pAnArray->data);
}
main()
{
     arrayContainerTen anArray;
     aFunction(&anArray);
}

Upvotes: 2

Barmar
Barmar

Reputation: 781130

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

Upvotes: 1

Related Questions