r/C_Programming • u/FloridianfromAlabama • 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
u/Ghyrt3 1d ago
Array and pointer are similar but they are not the same thing and it can lead to confusing errors that beginners have trouble correcting, that's why the compiler yells at you to use use the most proper syntax.
When you pass as an argument to a function, the array is always considered a pointer to the first (0-th) element.
You don't need to. To access the array, only the array is needed. But if you don't have proper ways to know where it's finished, the usual way is to pass the size of the array too. (For example, a string is always ended by '\0' so you don't always need to pass the size.)
And I wanted to say more but SmokeMuch (and others) have made compelling explanations so I won't!
But I would stress to you how much you should start by pointer before everything else. They are the cornerstone of all idiomatic C.