2

I am learning C and I have a problem understanding the difference between an array of integers and a pointer to it. More specifically,

int *array;
int size = atoi(argv[1]);
array = malloc(sizeof(int)*(size));

int len = read_array_from_file(array, atoi(argv[1]), filename);

merge_sort(array, 0, len-1);

what's confusing me is that the definition of the functions are

int read_array_from_file(int array[], size_t size, char *filename);
void merge_sort(int* array, int first, int last);

and both work just fine with 'array' as an argument, no error with its type. why is that?

1
  • 4
    C11 draft standard n1570: 6.7.6.3 Function declarators (including prototypes) 7 A declaration of a parameter as ‘‘array of type’’ shall be adjusted to ‘‘qualified pointer to type’’[...] Commented Jan 8, 2017 at 21:58

2 Answers 2

2

As a function parameter, int array[] is fully equivalent to int *array.

The purpose of [] there is to convey to the reader that the int * pointer that the function takes should probably point to an array rather than just a single int.

You can put qualifiers such as restrict or const inside the brackets to get the equivalents of int *restrict or int *const, and in C11, you can even do

int array[static MINIMUMS_SIZE] 

to convey the array param should have at least MINIMUM SIZE members. (clang checks this, gcc doesn't (last time I checked)).

int foo(int array[static 1])

(also C11) should effectively be equivalent to

int foo(int *array) __attribute__((__nonnull__));
//== please help me check I don't pass a NULL pointer

You can even do:

int foo(int n_items, int array[n_items]);

and pray the compiler will help you check this (it probably won't).

In any case, the basic and oldest rule is that arrays in parameters simply translate to pointers.

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

Comments

0

The reason for this is so-called "pointer decay". The type of the function is actually:

int read_array_from_file(int *array, size_t size, char *filename);
//                           ^ array changed to pointer

This is mandated by the C standard and happens specifically to function arguments.

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.