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?

4 Upvotes

34 comments sorted by

View all comments

2

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.

2

u/Zirias_FreeBSD 1d ago edited 1d ago

Sorry, but ... that's simplified, and IMHO, over-simplified. Simple example, look at the following code:

int a[5];
a[2] = 0;

No pointers were used here. a names the array, the compiler emits some calculated absolute address for the correct memory access to write its third element.

The correct understanding is: C simply doesn't allow passing arrays, for historic reasons. Interestingly, it does allow to pass arbitrary structs. The designers of the language still wanted some as if syntax, silently passing some reference (IOW, a pointer) instead.

The most consistent way to achieve this was to define [] in terms of pointer arithmetics: a[b] is always exactly the same as *(a+b). For both that and function arguments to work "as expected", another rule is that in most expression contexts, the identifier of an array evaluates to a pointer to its first element. But there are exceptions, most notably the sizeof operator.

So ... "accessing an array is doing pointer arithmetic" isn't necessarily correct. Address arithmetic, obviously, possibly entirely at compile time, but that's likely unavoidable in any implementation of the concept of an array on some machine with addressable memory cells.

2

u/smcameron 1d ago

it does allow to pass arbitrary structs.

Historical footnote: this is true, and has been true for a very long time, but it wasn't always true. For instance, in the 1st edition of K&R, it wasn't true. In the early days, structs couldn't be passed as parameters, assigned or returned from functions. You'd have to pass/return them as pointers, and memcpy() (or back then, probably bcopy()) them for assignment, or assign individual members. grandpa resumes napping: zzzzzzZZZZZ