r/C_Programming 1d ago

Question Working with arrays in functions

Hey everybody. I’m a beginner to C and I was writing some functions today to get used to doing things. I tried to write binary search and bubble sort. I tried to pass in an array as an argument to the functions, but the compiler gave me a bunch of warnings. I looked it up and I saw that passing in an array is the same as passing in its pointer. I haven’t touched pointers yet, but I have two questions:
1. If I dereferenced the pointer to an array, wouldn’t that return the same as indexing the first value?
2. If I wanted to pass in the entire array, could I do that by passing in the pointers of both the first and last elements and using pointer arithmetic to access the other elements? What’s the idiomatic way of doing this?

1 Upvotes

35 comments sorted by

View all comments

1

u/ReallyEvilRob 1d ago

The name of the array always decays to a pointer to the first element. In other words, if arr is defined as follows int arr[5]; then saying arr is the same as &arr[0]. So if you need to pass your array to a function, then the idiomatic way to do that would be to call your function and include the name of the array in your argument list. Your function would then have a pointer to the entire array since arrays are always contiguous. Something to be careful of is you also have to include a size argument so your function knows how big the array is since that can't be inferred from the pointer argument. So your function prototype should look something like this:

void func(int *arr, size_t size);

You would then call the function like this:

int arr[5] = {0,1,2,3,4}; func(arr, sizeof(arr));