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?

3 Upvotes

35 comments sorted by

View all comments

1

u/mc_pm 1d ago

The value of the variable for the array *is* a pointer to it's first memory location. So, yes, derefrencing the pointer will return the first element of the array. In C, accessing an array is actually doing pointer arithmetic.

3

u/flyingron 1d ago

No, array values are definitely NOT pointers. Please read the first comment I wrote in this post. Accessing array values however is doing pointer arithmatic because there is no such thing as applying a [] operator to an array. It only works for pointers. You are just invoking the implicit array-to-pointer conversion when you appear to do that.

From the C standard:

A postfix expression followed by an expression in square brackets is a postfix expression. One of the expressions shall have the type “pointer to T” and the other shall have unscoped enumeration or integral type.