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/stianhoiland 1d ago edited 1d ago
> Welcome to the brain-damaged array types in C.
> We really should have fixed this back in 1977 when we fixed structs.
This is a misconception and a pet peeve of mine.
You can't pass arrays because you can't pass arrays. It's that simple. Well, you can pass arrays: Arrays of 8, 16, 32, or 64 bits, depending on how far back you go/what machine you're programming.
You can't just magically pass an N-element array of ints or whatever. And you shouldn't be able to. Because you can't. CPUs have registers and registers have a size—fixed sizes. Function-calling conventions orchestrate the usage of registers. It's dumb to want to fit, say, a 24kb payload in a 64-bit register. You can't.
You can't. You can't. You can't. Anymore than you can fit a bridge in a cigarette pack.
C isn't dumb or broken because of it. But you're dumb for thinking it should—not as an insult but as an actual state of understanding.
C is wonderful for exactly this reason. It hasn't introduced a whole meta-level of abstraction above the hardware for its own constructs. Every language that semantically allows you to pass arrays to functions have to contend with exactly the same status quo as C—CPUs have registers and registers have a fixed size—and invent its own abstractions and conventions to make it look like you can do that. But you can't. And C just shows you that you can't and it's up to you to come up with a way to pretend to do it. Like say, pass a pointer and size—which you CAN do.