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!

7
  • Why not use int foo (int arg[/*10*/]);? Commenting the dimension Commented Mar 10, 2015 at 18:07
  • Why not use int foo (int *arg, int elements);? Commented Mar 10, 2015 at 18:08
  • possible duplicate of C Parameter Array Declarators Commented Mar 10, 2015 at 18:09
  • @WeatherVane It's intended for humans, as a way to let them know that the array should always have 10 elements. Commented Mar 10, 2015 at 18:09
  • You can wrap the array to a struct and pass a pointer to that struct in. Arrays in structs have size info. Commented Mar 10, 2015 at 18:10

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.
2
struct arrayContainerTen{
  int data[10];
}
void aFunction(struct arrayContainerTen *pAnArray)
{
    size_t size = sizeof(pAnArray->data);
}
main()
{
     arrayContainerTen anArray;
     aFunction(&anArray);
}

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.