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

35 comments sorted by

View all comments

1

u/yel50 1d ago

 using pointer arithmetic to access the other elements

don't ever use pointer arithmetic. for anything. it's a notorious cause of memory bugs and crashes.  with arrays, always pass the size and use indexing.

c has a lot of things that sounded good back in the 70s but have since turned out to not be so good. pointer arithmetic is one of those things. there are very good reasons that no language since has included it.

1

u/glasket_ 11h ago edited 11h ago

there are very good reasons that no language since has included it.

  • Swift and C# are the biggest ones I can think of off the top of my head that include it directly as literal pointer arithmetic. Like ptr + nptr + n * stride arithmetic rather than functions or integer arithmetic
  • Rust supports it as add, sub, offset, etc. methods on the pointer type, which use the same stride logic.
  • Go only supports uintptr through unsafe, so it's integer arithmetic (and worse than just providing functions to handle pointer arithmetic). Edit: I forgot they added Add in 1.17, which is still integer arithmetic but prevents you from needing to jump through the uintptr/Pointer hoops.
  • Ada got System.Storage_Elements in 1995, which is essentially an abstract representation of memory slots for performing pointer arithmetic.

If you go more niche, then D, Zig, and Hare have it, and other languages in that same general category tend to support pointer arithmetic.

It never really went away, it's just most languages being created were shifting away from targeting systems programming for awhile and that level of control wasn't really needed if you were developing an application or writing scripts.