Reputation: 2967
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
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:
In the function, you have to use:
(*arg)[index]
instead of just
arg[index]
The calling function must use:
int array[10];
foo(&array);
instead of
int array[10];
foo(array);
You cannot use an array that has more than 10 elements.
int array[20];
foo(&array); // Not OK.
You cannot use a malloc
ed array.
int* array = malloc(sizeof(int)*10);
foo(array); // Not OK.
Now pick the solution that is least harmful.
Upvotes: 2
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
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